流<<运算符没有被调用

发布于 2025-01-15 13:49:44 字数 730 浏览 2 评论 0 原文

我创建了一个具有一些基本属性的 Animal 类,并添加了一个无数据构造函数。 我还重载了 ostream 运算符来打印属性。

Animal.cpp

#include<bits/stdc++.h> 
using namespace std;

class Animal {
    string name;
    int action;
public: 
    Animal() {
        name = "dog";
        action = 1;
    }
    ostream& write(ostream& os) {
        os << name << "\n" << action << "\n";
        return os;
    }
    friend ostream& operator<<(ostream& os, Animal &animal) {
        return animal.write(os);
    }
};



int main() {
    cout << "Animal: " << Animal() << "\n";
}

但是,我在主要错误中发现二进制表达式 ostream 和 Animal 的操作数无效。 如果我声明 Animal 然后调用 cout,效果很好。但是如何让它像这样工作(同时初始化和cout)?

I have created a class Animal with some basic properties and added a no data constructor.
I have overloaded the ostream operator as well to print the properties.

Animal.cpp

#include<bits/stdc++.h> 
using namespace std;

class Animal {
    string name;
    int action;
public: 
    Animal() {
        name = "dog";
        action = 1;
    }
    ostream& write(ostream& os) {
        os << name << "\n" << action << "\n";
        return os;
    }
    friend ostream& operator<<(ostream& os, Animal &animal) {
        return animal.write(os);
    }
};



int main() {
    cout << "Animal: " << Animal() << "\n";
}

However I am getting error in the main that invalid operands to binary expression ostream and Animal.
It works fine if I declare Animal and then call the cout. But how to make it work like this (initialize and cout at the same time) ?

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

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

发布评论

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

评论(1

夏末的微笑 2025-01-22 13:49:44

operator<< 的第二个参数声明为 Animal &Animal() 是临时的,不能绑定到非常量的左值引用。

您可以将类型更改为 const Animal &;临时可以绑定到 const 的左值引用。 (然后 write 也需要标记为 const。)

class Animal {
    string name;
    int action;
public: 
    Animal() {
        name = "dog";
        action = 1;
    }
    ostream& write(ostream& os) const {
        os << name << "\n" << action << "\n";
        return os;
    }
    friend ostream& operator<<(ostream& os, const Animal &animal) {
        return animal.write(os);
    }
};

The 2nd parameter of operator<< is declared as Animal &; Animal() is a temporary and can't be bound to lvalue-reference to non-const.

You can change the type to const Animal &; temporary could be bound to lvalue-reference to const. (Then write needs to marked as const too.)

class Animal {
    string name;
    int action;
public: 
    Animal() {
        name = "dog";
        action = 1;
    }
    ostream& write(ostream& os) const {
        os << name << "\n" << action << "\n";
        return os;
    }
    friend ostream& operator<<(ostream& os, const Animal &animal) {
        return animal.write(os);
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文