可以在派生类中运算符<<在c ++的基类中调用另一个运算符<<吗?

ivo*_*ory 1 c++ operator-overloading derived-class operator-keyword

在我的代码中,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;
}
Run Code Online (Sandbox Code Playgroud)

我希望cout << (Employee)m << endl;会打电话ostream& operator<< (ostream& out, Employee& e),但它失败了.

izo*_*ica 7

转换为引用而不是副本:

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

还要注意,ostream运算符绝不是类的成员(看起来你对问题的标题感到困惑).