ostream << 运算符未被调用

ostream << operator not getting invoked

我创建了一个具有一些基本属性的 class 动物,并添加了一个无数据构造函数。 我还重载了 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)?

operator<<的第二个参数声明为Animal &Animal() 是临时的,不能绑定到 lvalue-reference 到 non-const。

您可以将类型更改为const Animal &; temporary 可以绑定到 lvalue-reference 到 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);
    }
};