运算符<<和继承

Jav*_*cia 2 c++ inheritance operators friend

我在C ++中具有以下类:

class Event {
        //...
        friend ofstream& operator<<(ofstream& ofs, Event& e);

};


class SSHDFailureEvent: public Event {
    //...
    friend ofstream& operator<<(ofstream& ofs, SSHDFailureEvent& e);
};
Run Code Online (Sandbox Code Playgroud)

我要执行的代码是:

main(){

 Event *e = new SSHDFailureEvent();
 ofstream ofs("file");
 ofs << *e; 
Run Code Online (Sandbox Code Playgroud)

}

这是一种简化,但是我要做的是将文件中几种类型的事件写入文件。但是,它不使用SSHDFailureEvent的运算符<<,而是使用Event的运算符<<。有什么办法可以避免这种行为?

谢谢

Naw*_*waz 6

那将行不通,因为这将需要operator<<基类。

您可以print在基类中定义一个虚函数,然后重新定义所有派生类,并且operator<<只定义一次,

class Event {

      virtual ofstream& print(ofstream & ofs) = 0 ; //pure virtual  

      friend ofstream& operator<<(ofstream& ofs, Event& e);
};

//define only once - no definition for derived classes!
ofstream& operator<<(ofstream& ofs, Event& e)
{
   return e.print(ofs); //call the virtual function whose job is printing!
}
Run Code Online (Sandbox Code Playgroud)