[英]passing an unnamed object as an argument when making a new object in C++
我想在構造函數中使用未命名的 object 作為參數,但它會產生以下錯誤。
我猜 object 名稱 'b2' 被解釋為 function 原型或其他東西。
class AAA
{
private:
int m_val;
public:
AAA(int a) : m_val(a) {}
};
class BBB
{
private:
AAA a;
public:
BBB(AAA &a_) : a(a_) {}
};
int main()
{
AAA a(5), a1(10);
BBB b(a), b1(a1);
b = b1;
BBB b2(AAA());
b = b2;
}
.\ex_unnamed.cpp: In function 'int main()':
.\ex_unnamed.cpp:21:9: error: no match for 'operator=' (operand types are 'BBB' and 'BBB(AAA (*)())')
b = b2;
^~
.\ex_unnamed.cpp:8:7: note: candidate: 'constexpr BBB& BBB::operator=(const BBB&)'
class BBB
^~~
.\ex_unnamed.cpp:8:7: note: no known conversion for argument 1 from 'BBB(AAA (*)())' to 'const BBB&'
.\ex_unnamed.cpp:8:7: note: candidate: 'constexpr BBB& BBB::operator=(BBB&&)'
.\ex_unnamed.cpp:8:7: note: no known conversion for argument 1 from 'BBB(AAA (*)())' to 'BBB&&'
首先,這並不意味着您認為它意味着什么:
BBB b2( AAA() );
b2
實際上被編譯器解釋為一個名為b2
的 function 的聲明,它接受一個 function 指針,該指針返回一個AAA
作為參數,並返回一個BBB
。
對於我的編譯器,請查看簽名:
所以這失敗了:
b = b2;
因為BBB
沒有賦值運算符,它采用 function 等。
您可以通過執行以下操作來解決此問題:
int main()
{
AAA a(5), a1(10);
BBB b(a), b1(a1);
b = b1;
BBB b2( AAA(5) );
b = b2;
}
但它仍然無法編譯。 這是因為BBB
需要參考實際的AAA
object。
要解決此問題,由於您實際上並未更改傳遞的AAA
object,因此我建議您將BBB
的構造函數更改為:
BBB(const AAA& a_) : a(a_) {}
畢竟, BBB::a
只是BBB
的構造函數中傳遞的參數的副本。 最終結果:
class AAA
{
private:
int m_val;
public:
AAA(int a) : m_val(a) {}
};
class BBB
{
private:
AAA a;
public:
BBB(const AAA& a_) : a(a_) {}
};
int main()
{
AAA a(5), a1(10);
BBB b(a), b1(a1);
b = b1;
BBB b2( AAA(5) );
b = b2;
}
有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.