class A {
//does stuff
public:
virtual std::ostream& operator<< (std::ostream& os) = 0;
};
class B : public A {
public:
//does similiar stuff
virtual std::ostream& operator<< (std::ostream& os) {
os << "x" << std::endl;
}
}
class C {
public:
A* array[10];
A* & operator()(int a) {
// in my code, it is a 2D array indexed with (),
// but that's irrelevant here
return array[a];
}
}
int main(){
C c = C();
//in for loop we say c(i) = new B();
for(int i=0; i<10; i++){
std::cout << *(c(i)); // error
}
return 0;
}
我猜测问题是my()运算符返回基指针而不是B的指针而A没有<<。但是使用模板进行索引并没有解决问题,它只是让它更奇怪。
有任何想法吗?
问题是你将operator<<
作为成员函数重载。这意味着它只能用作例如
instance_of_B << std::cout;
这被翻译成
instance_of_B.operator<<(std::cout);
如果要将<<
重载为流输出运算符,则它必须是非成员函数,并将流作为第一个参数,将A
(或派生)对象作为第二个参数。
要处理输出,您可以使用执行此操作的虚拟成员函数,并由非成员operator<<
函数调用。
也许是这样的
class A
{
public:
...
// Inline definitions of friend functions makes the functions non-member functions
friend std::ostream& operator<<(std::ostream& os, A const& a)
{
return a.output(os);
}
protected:
virtual std::ostream& output(std::ostream&) = 0;
};
class B
{
...
protected:
std::ostream& output(std::ostream& os) override
{
return os << "Output from the B class\n";
}
};