用于类函数的C ++提取运算符 [英] C++ Extraction Operator for Class Functions

查看:162
本文介绍了用于类函数的C ++提取运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定运算符重载是我在找什么,但我需要知道在C ++中实现以下内容的最佳方式;



I有一个班级员工(为了简单)只有一个身份证号码atm。请假设输入文件有一个int数字和一些字符(仅显示1行),例如:
$ b $ 1234 Charles Hammond

这是迄今为止的代码。我试图使用提取操作符来获取输入文件中的整数和其他数据到我的类函数(SetID);

  class Employee 
{
int employeeID;

public:
void SetID(int);


Employee Employee :: SetID(int empID)
{
employeeID = empID;


int main(void)
{
int lineCounter = 4;
雇员雇员;

//创建文件流对象并打开
ifstream输入;
ofstream输出;
input.open(input.txt);
output.open(output.txt);


for(int i = 0; i< lineCounter; i ++)
{
input>> emp.SetID(input.get()); //非法?最好的办法做到这一点


$ b //关闭程序
output.close();
input.close();
系统(暂停);
返回0;

$ / code>

我只是试图从输入文件中获取ID并将其存储稍后将用于计算的类成员employeeID。

解决方案

一个选项是重载>> 使它成为你的Employee类中的朋友函数。



  istream的&安培;运营商>>(istream& in,Employee& emp)
{
in>> emp.employeeID;
返回;





在你的Employee类中:

  friend istream&运营商GT;> (istream& in,Employee& emp); 


I'm not sure if operator overloading is what I'm looking for, but I need to know the best way to achieve the following in C++;

I have a class Employee (for simplicity) with just an ID number atm. Please assume the input file has an int number and some characters after (1 line shown only), such as:

1234 Charles Hammond

Here is the code so far. I am trying to use the extraction operator to get the integer and other data from input file to my class function (SetID);

class Employee
{
    int employeeID;

public:
     void SetID(int);
}

void Employee::SetID(int empID)
{
    employeeID = empID;
}

int main(void)
{
    int lineCounter = 4;
    Employee emp;

    //Create filestream objects and open
    ifstream input;
    ofstream output;
    input.open("input.txt");
    output.open("output.txt");


    for (int i = 0; i < lineCounter; i++)
    {
        input >> emp.SetID(input.get()); //illegal? Best way to do this
    }


    //Close program
    output.close();
    input.close();
    system("pause");
    return 0;
}

I am simply trying to get the ID from the input file and store it in the class member "employeeID" to be used for calculations later.

解决方案

One option is to overload the >> operator and make it a friend function in your Employee class.

Something like:

istream& operator>>( istream& in, Employee& emp )
{
    in >> emp.employeeID;
    return in;
}

And in your Employee class:

friend istream& operator>> (istream& in, Employee& emp);

这篇关于用于类函数的C ++提取运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆