使运算符<<虚拟的?
我需要使用虚拟 <<操作员。但是,当我尝试编写:
virtual friend ostream & operator<<(ostream& os,const Advertising& add);
我收到编译器错误
错误 1 错误 C2575:“运算符 <<” : 只能是成员函数和基数 虚拟
如何将该操作员转为虚拟?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您定义您的运算符 <<调用虚拟打印方法:
You define your operator << to call a virtual print method:
看起来您确实想为类层次结构提供输出功能,如果是这样,您可以提供一个调用
虚拟
函数的友元运算符<<
。另请参阅 C++ 常见问题解答
It looks like you really want to provide output functionality for a hierarchy of classes, and if so, you can provide a
friend operator <<
that calls avirtual
function.Also detailed in the C++ FAQ
此设置的问题在于您上面定义的运算符<<是一个自由函数,它不能是虚拟的(它没有接收者对象)。为了使函数成为虚拟函数,必须将其定义为某个类的成员,这在这里是有问题的,因为如果将
operator<<
定义为类的成员,那么操作数将位于错误的顺序:意味着
不会编译,但
会合法。
要解决此问题,您可以应用软件工程基本定理 - 任何问题都可以通过添加另一层间接来解决。不要将
operator<<
设为虚拟,而是考虑向类中添加一个新的虚函数,如下所示:然后,将
operator<<
定义为这样,< code>operator<< 自由函数具有正确的参数顺序,但
operator<<
的行为可以在子类中自定义。The problem with this setup is that the
operator<<
you defined above is a free function, which can't be virtual (it has no receiver object). In order to make the function virtual, it must be defined as a member of some class, which is problematic here because if you defineoperator<<
as a member of a class then the operands will be in the wrong order:means that
will not compile, but
will be legal.
To fix this, you can apply the Fundamental Theorem of Software Engineering - any problem can be solved by adding another layer of indirection. Rather than making
operator<<
virtual, consider adding a new virtual function to the class that looks like this:Then, define
operator<<
asThis way, the
operator<<
free function has the right parameter order, but the behavior ofoperator<<
can be customized in subclasses.