c++ - cout 上抽象类的多态性

标签 c++ class polymorphism operator-overloading

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

我想在父亲身上写运算符(operator)<<并在儿子身上实现

这里是代码

#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 error C2852: 'operator <<' : only data members can be initialized within a class

错误 2 error C2575 : 'operator <<' : only member functions and bases can be virtual

错误 1 ​​错误 C2254:“<<”:友元函数上不允许纯说明符或抽象覆盖说明符

请问我能做什么?

最佳答案

虽然你不能让一个运算符(operator)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 .

关于c++ - cout 上抽象类的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33711460/

相关文章:

c# - List.Contains 对象比较失败

C++ 虚函数基返回类型建议

c++ - 是否有指向成员特征或类似内容的指针?

c++ - 与 gdb 一起使用的 Makefile

javascript - 从类返回字符串 - JavaScript

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

当我不知道 child 的类型时,C++ 从基类调用子类函数

c++ - 从 int 到 char* 没有字符串,和 fstream 不方便

c++ - 在这种情况下调用什么构造函数?

c++ - STACK.peek 函数,遇到一些问题,C++