ostream operator<<没有执行

时间:2012-02-02 20:16:52

标签: c++ operator-keyword ostream

所以我自己编写了这段代码,但是从其他示例代码中获取...

class A{
    friend std::ostream& operator<< (std::ostream& out, A& a);
    // Constructors, destructor, and variables have been declared
    // and initialized and all good.
}

std::ostream& operator<< (std::ostream& out, A& a){
    out << " this gets written " << endl; // it doesn't get executed
    return out;
}

int main(){
    A *_a = new A();
    return 0;
}

而且,这不是在控制台" this gets written "

中打印

1 个答案:

答案 0 :(得分:1)

如果您尝试通过std::cout << a或类似的方式使用运算符,则问题是您将指针传递给对象,而<<运算符定义为将引用带到对象。您需要将a声明为常规(非指针)A,或使用std::cout << *a