cout上抽象类的多态性

polymorphism with abstract class on cout

本文关键字:多态性 抽象类 cout      更新时间:2023-10-16

我有抽象类(类"父亲")和子类

我想写父亲的话务员<lt;并在子上实现

这里是代码

#include <iostream>
using namespace std;
class father {
    virtual friend ostream& operator<< (ostream & out, father &obj) = 0;
};
class son: public father  {
    friend ostream& operator<< (ostream & out, son &obj)
    {
        out << "bla bla";
        return out;
    }
};
void main()
{
    son obj;
    cout << obj;
}

我得到3个错误

错误3错误C2852:"operator<lt;':在类中只能初始化数据成员

错误2错误C2575:"operator<lt;':只有成员功能和基地可以是虚拟

错误1错误C2254:"<lt;':朋友函数上不允许使用纯说明符或抽象重写说明符

我能做什么?

虽然您不能使运算符virtual,但您可以使它们调用一个常规的虚拟函数,如下所示:

class father {
    virtual ostream& format(ostream & out, father &obj) = 0;
    friend ostream& operator<< (ostream & out, father &obj) {
        return format(out, obj);
    }
};
class son: public father  {
    virtual ostream& format(ostream & out, son &obj) {
        out << "bla bla";
        return out;
    }
};

现在只有一个operator <<,但father的每个子类都可以通过重写虚拟成员函数format来提供自己的实现。