[英]Can I assign a const reference to a non-const variable?
假設我定義了以下運算符:
const int & operator= (const MyClass &);
我可以用它來對非常量變量進行賦值嗎?
閱讀此處的評論,我的理解是,是的,我可以(即即使 a 不是const
並且編譯器不會抱怨,我也可以做a=b
之類的事情)。
但是,當我嘗試以下代碼時:
int main()
{
int x = 42;
const int &y = x; // y is a const reference to x
int &z = y;
}
它失敗並顯示以下內容:
compilation
execution
main.cpp:9:8: error: binding reference of type 'int' to value of type 'const int' drops 'const' qualifier
int &z = y;
^ ~
1 error generated.
是的,您可以將 const 引用分配給非引用變量。
int x = 42;
const int &y = x; // y is a const reference to x
int w = y; // this works
int z& = y; // this doesn't
您可以將 const 引用分配給非引用,因為該值已被復制,這意味着如果w
被修改,則x
不會被修改,因為w
是數據的副本。
您不能將 const 引用分配給非 const 引用,因為當您使用 const 引用時,您保證不會修改指向的值。 如果您被允許將 const 引用分配給非 const 引用,您將違反此保證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.