我創建了一個具有一些基本屬性的類 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";
}
但是,我主要收到錯誤,即二進制運算式 ostream 和 Animal 的運算元無效。如果我宣告 Animal 然后呼叫 cout,它作業正常。但是如何讓它像這樣作業(同時初始化和 cout)?
uj5u.com熱心網友回復:
的第二個引數operator<<宣告為Animal &;Animal()是一個臨時的,不能系結到非 const 的左值參考。
您可以將型別更改為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);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/446819.html
