使运算符<<虚拟? [英] Making operator<< virtual?

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

问题描述

我需要使用虚拟<<运算符。然而,当我尝试写:

  virtual friend ostream& operator<<(ostream& os,const Advertising& add); 

我得到编译器错误


错误1错误C2575:'operator <<::
只有成员函数和基数可以是
virtual


$ b $

解决方案

这个设置的问题是,运算符< ;&你定义的是一个自由函数,它不能是虚拟的(它没有接收者对象)。为了使函数成为虚拟的,它必须被定义为某个类的成员,这在这里是有问题的,因为如果定义operator<<作为类的成员,那么操作数的顺序将是错误的:

  class MyClass {
public:
virtual ostream&运算符<< (ostream& out)const;
};

表示

  MyClass myObject; 
cout<< myObject;

无法编译,但

  MyClass myObject; 
myObject<< cout;

将是合法的。



这可以应用软件工程的基本定理 - 任何问题都可以通过添加另一层间接来解决。而不是使得操作员< virtual,考虑向类添加一个新的虚拟函数,如下所示:

  class MyClass {
public:
virtual void print(ostream& where; const;
};然后,定义运算符<<< p>< / b> as

  ostream&运算符<< (ostream& out,const MyClass& mc){
mc.print(out);
return out;
}

这样操作符<自由函数具有正确的参数顺序,但是操作符<<可以在子类中自定义。



希望这有助于!


I need to use a virtual << operator. However, when I try to write:

virtual friend ostream & operator<<(ostream& os,const Advertising& add);

I get the compiler error

Error 1 error C2575: 'operator <<' : only member functions and bases can be virtual

How can I turn this operator virtual?

解决方案

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 define operator<< as a member of a class then the operands will be in the wrong order:

class MyClass {
public:
    virtual ostream& operator<< (ostream& out) const;
};

means that

MyClass myObject;
cout << myObject;

will not compile, but

MyClass myObject;
myObject << cout;

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:

class MyClass {
public:
    virtual void print(ostream& where) const;
};

Then, define operator<< as

ostream& operator<< (ostream& out, const MyClass& mc) {
    mc.print(out);
    return out;
}

This way, the operator<< free function has the right parameter order, but the behavior of operator<< can be customized in subclasses.

Hope this helps!

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

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