c++ - std::cin 中的运算符 >> 不匹配

标签 c++ debugging operator-overloading

我有类(class)员工

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class employee
{
    public:

            double operator + (employee);
            istream& operator>> (istream&);

            employee(int);
            double getSalary();

    private:

           double salary;

};

int main()
{  
  employee A(400);
  employee B(800);

  employee C(220);

  cin>>C;

}

employee::employee(int salary)
{
    this->salary = salary;
}


double employee::operator + (employee e)
{
    double total;

    total = e.salary + this->salary;

    return total;    
}


double employee::getSalary()
{
    return this->salary;
}

istream& employee::operator>> (istream& in)
{
    in>>this->salary;

    return in;

}

我试图重载输入运算符 >> 以读取员工对象,但出现以下错误

no match for operator >> in std::cin

我做错了什么???

编辑:我知道如何通过友元函数做到这一点,我现在正在尝试学习如何通过成员函数做到这一点

最佳答案

I know how to do it through a friend function , i am now trying to learn how to do it through a member function

你不能。

对于二进制 operator@和对象 A aB b , 语法 a @ b将调用 或者 形式为 operator@(A,B) 的非成员函数 A::operator@(B) 形式的成员函数.没有别的。

所以要std::cin >> C它必须作为 std::istream 的成员工作, 但由于您无法修改 std::istream你不能实现 operator>>作为成员函数。

(除非你想变得怪异和标新立异并写成 C << std::cinC >> std::cin ,但如果你这样做,其他程序员会因为你的困惑和标新立异而讨厌你。不要这样做。)

关于c++ - std::cin 中的运算符 >> 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218520/

相关文章:

c++ - 何时在 C++ 方法声明的开头和结尾使用 const

c# - 数组被C#虚拟机写保护

c++ - Qt 应用程序不在 Qt Creator 中执行

c++ - 如何使用 pdb 调试现有的 C++ 可执行文件但没有源代码

C++ 重载加法无法正常工作

c++ - 如何在 Qt 中合并两个 QJsonObjects?

windows - 将 DebugDiag 与内部应用程序结合使用

node.js - 如何调试 yeoman 应用程序?

delphi - 子范围和运算符重载