在我的代码中,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/