cout上抽象类的多态性
polymorphism with abstract class on cout
我有抽象类(类"父亲")和子类
我想写父亲的话务员<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
来提供自己的实现。
相关文章:
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- C++模板方法重载和具有多态性的类访问
- 没有新成员的模板多态性派生类的大小
- 从具有多态性的类中检索数据
- 多态性抽象语法树(递归下降解析器):不可能
- 多态性:通过类文本或对象访问静态成员
- c++多态性:基类的上转换/下转换和容器,缺少数据
- C++多态性模板类:调用基类方法而不是派生类
- C++中的多态性和类抽象实例
- 多态性c++,试图访问从抽象基类派生的类的成员函数
- cout上抽象类的多态性
- 多态性:实例类
- c++中多态性基类和继承类实例化的问题
- 用于智能指针(intrusive_ptr)的抽象基类-处理继承性、多态性、可克隆性和从工厂返回的方法
- 抽象类和多态性
- 多态性基类指针
- C++抽象类和多态性
- 具有抽象类的多态性(C++)
- 抽象基类w/o多态性
- C++ 多态性 - 继承类的映射