运算符<<和继承 [英] Operator << and inheritance

查看:85
本文介绍了运算符<<和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following classes in C++:

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

};


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

我要执行的代码是:

main(){

 Event *e = new SSHDFailureEvent();
 ofstream ofs("file");
 ofs << *e; 

}

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

This is a simplification, but what I want to do is write into a file several type of Events in a file. However, instead of using the operator << of SSHDFailureEvent, it uses the operator << of Event. Is there any way to avoid this behavior?

谢谢

推荐答案

那是行不通的,因为它将为基类调用 operator<< .

That would not work, as that would call operator<< for the base class.

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

You can define a virtual function print in base class and re-define it all derived class, and define operator<< only once as,

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!
}

这篇关于运算符&lt;&lt;和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆