派生类的重载<<运算符表示操作数无效


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;
}

我猜想问题是我的()运算符用基本指针返回,而不是B的指针,A没有LT;&lt;。但是,将模板用于索引也无法解决问题,它只是使其更奇怪。

有什么想法?

问题是,您将operator<<作为A 成员函数超载。这意味着它只能用作例如。

instance_of_B << std::cout;

被翻译成

instance_of_B.operator<<(std::cout);

如果要将<<作为流量输出操作员重载,则必须是 non -Member函数,并将流作为第一个参数和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 classn";
    }
};

相关内容

最新更新