类函数的 C++ 提取运算符

标签 c++ file-io io operator-overloading iostream

我不确定运算符重载是否是我要找的东西,但我需要知道在 C++ 中实现以下目标的最佳方法;

我有一个 Employee 类(为简单起见),它只有一个 ID 号 atm。请假设输入文件有一个 int 数字和后面的一些字符(仅显示 1 行),例如:

1234 查尔斯·哈蒙德

这是到目前为止的代码。我正在尝试使用提取运算符将整数和其他数据从输入文件获取到我的类函数 (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;
}

我只是想从输入文件中获取 ID 并将其存储在类成员“employeeID”中,以便稍后用于计算。

最佳答案

一个选择是重载 >>> 运算符并使其成为您的 Employee 类中的友元函数。

类似于:

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

在您的 Employee 类中:

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

关于类函数的 C++ 提取运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23925866/

相关文章:

c++ - 使用 libdbus-c++ 获得了 DBus::Path - 下一步是什么?

c++ - 在 OpenCV 中使用 Mat 时的 exc_bad_access 虽然看起来我的索引是正确的

c - 将数百万次写入文件会破坏我的硬盘吗?

C++ - 从抽象基指针调用派生函数

c++ - 无法使用 net stop 命令停止 Windows 服务

c# - 使 Directory.GetFiles() 忽略 protected 文件夹

mysql - 来自 .CSV 的 'LOAD DATA INFILE' 警告 - 整数和日期

c# - File.Move 引起的 System.IO.DirectoryNotFoundException

c++ - 如何在 C++ 控制台应用程序中输出波兰语字符?

stream - 如何在 Go 中读取至少 N 个字节