我有抽象课(“父亲”课)和儿子课

我想在父亲身上写操作符<
这里的代码

#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:“运算符<
错误2错误C2575:“运算符<
错误1错误C2254:“ <
我能做什么?

最佳答案

尽管不能使运算符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提供自己的实现。

07-21 10:48