c++ - 使 operator<< 成为虚拟的?

标签 c++ operators operator-overloading virtual

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

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/

相关文章:

c++ - try-catch block 是否会降低性能

c++ - 作为函数参数传递的 vector 初始值设定项列表

c++ - 为什么在文件 I/O 中读取数据 block 比逐字节读取更快

c++ - C++ (Visual Studio 6) 中 operator< 和 operator[] 的默认返回值是什么?

c# - 为什么按位运算符不如逻辑 "and\or"运算符聪明

c++ - 运算符重载为友元函数

c++ - 为什么没有类似于 std::string_view 的 view<T>

c# - 为什么我们的 C# 图形代码不再工作了?

c++ - 在成员函数中使用 operator()

c++ - 重载智能指针指向的成员函数