[英]How to cout a constructor?
我是C ++的新手,我在學習它時遇到了這個問題
所以我創建了這個類
class A {
int num;
public:
//constructor
A(int num) {
this->num = num;
}
int getNum() {
return num;
}
//overload <<
friend ostream& operator << (ostream& os,A& a) {
os << a.getNum();
return os;
}
};
在main函數中,如果我使用cout<< A(1);
它編譯錯誤(Visual Studio 2017中的代碼C2679)。
我怎樣才能像cout<< int(1);
? 我是否需要超載任何其他運營商?
你的重載需要采用const A&
,否則匿名臨時 A(1)
不能綁定它。
另一種方法是使用rvalue references
重載operator <<
friend ostream& operator << (ostream& os, A&& a) {
os << a.getNum();
return os;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.