c++ - 派生类中的 operator<< 可以在 C++ 的基类中调用另一个 operator<< 吗?

标签 c++ operator-overloading operator-keyword derived-class

在我的代码中,Manager源自 Employee他们每个人都有一个 operator<<覆盖。

class Employee{
protected:
    int salary;
    int rank;
public:
    int getSalary()const{return salary;}
    int getRank()const{return rank;}
    Employee(int s, int r):salary(s), rank(r){};
};
ostream& operator<< (ostream& out, Employee& e){
    out << "Salary: " << e.getSalary() << " Rank: " << e.getRank() << endl;
    return out;
}

class Manager: public Employee{
public:
    Manager(int s, int r): Employee(s, r){};
};
ostream& operator<< (ostream& out, Manager& m){   
    out << "Manager: ";
    cout << (Employee)m << endl;  //can not compile, how to call function of Employee?
    return out;
}

我希望cout << (Employee)m << endl;会调用ostream& operator<< (ostream& out, Employee& e) , 但它失败了。

最佳答案

转换为引用而不是拷贝:

cout << (Employee&)m << endl;  //can not compile, how to call function of Employee?

另请注意,ostream 运算符绝不是该类的成员(从问题的标题来看,您似乎对此感到困惑)。

关于c++ - 派生类中的 operator<< 可以在 C++ 的基类中调用另一个 operator<< 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19710685/

相关文章:

c++ - 不同类如何操作一个函数一个

C++ 运算符 + 重载

c++ - 将(文本文件)转换为任何格式的图像(png)C++

c++ - CRT 静态链接的 COM InProc 服务器的资源(例如 FLS 索引)耗尽

c++ - 函数A调用函数B,函数B调用函数A,你怎么调用它?

C++ 重载 + 运算符只有成员函数用于添加带有整数的类对象

c++ - 重载运算符中具有静态函数的模板与具有非静态函数的对象

c# - 警告 MSB3270 : mismatch between the processor architecture of the project

c++ - 在 C++ 中使用前缀重载运算符 <<

javascript - JS 中的 "|="运算符(以前从未见过)