ostream << 运算符未被调用

Pra*_*nha 1 c++ oop overloading ostream

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

动物.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";
}
Run Code Online (Sandbox Code Playgroud)

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

son*_*yao 5

的第二个参数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);
    }
};
Run Code Online (Sandbox Code Playgroud)