ostream 运算符 <<不执行

发布于 2025-01-01 11:23:34 字数 529 浏览 0 评论 0 原文

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

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 write "

So I have this code written by myself but taken from other example codes...

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

And well, this is just not printing in the console " this gets written "

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久伴你 2025-01-08 11:23:34

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

If you're attempting to use the operator via std::cout << a or something similar, the problem is you're passing a pointer to an object, while the << operator is defined as taking a reference to an object. You either need to declare a as regular (non-pointer) A, or use std::cout << *a.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文