我有抽象类(类“父亲”)和儿子类
我想在父亲身上写运算符(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/