我需要使用虚拟 << 运算符。但是,当我尝试写:
virtual friend ostream & operator<<(ostream& os,const Advertising& add);
我得到编译器错误
Error 1 error C2575: 'operator <<' : only member functions and bases can be virtual
我怎样才能把这个算子变成虚拟的?
最佳答案
这个设置的问题是你上面定义的 operator<< 是一个自由函数,它不能是虚拟的(它没有接收器对象)。为了使函数成为虚拟函数,必须将其定义为某个类的成员,这在这里是有问题的,因为如果将 operator<< 定义为类的成员,那么操作数的顺序将是错误的:
class MyClass {
public:
virtual ostream& operator<< (ostream& out) const;
};
意思是
MyClass myObject;
cout << myObject;
不会编译,但是
MyClass myObject;
myObject << cout;
将是合法的。
要解决此问题,您可以应用软件工程基本定理 - 任何问题都可以通过添加另一层间接来解决。与其将 operator<< 设为虚拟,不如考虑在类中添加一个新的虚拟函数,如下所示:
class MyClass {
public:
virtual void print(ostream& where) const;
};
然后,定义运算符<< as
ostream& operator<< (ostream& out, const MyClass& mc) {
mc.print(out);
return out;
}
这样,operator<<自由函数的参数顺序是正确的,但是operator<<的行为可以在子类中自定义。
希望这会有所帮助!
关于c++ - 使 operator<< 成为虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4571611/