由于我的 C 程式中出現以下錯誤,我想到了這個問題
#include <iostream>
using namespace std;
class Test
{
private:
int x;
public:
Test(int x = 0) { this->x = x; }
void change(Test *t) { this = t; }
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj(15);
Test *ptr = new Test (100);
obj.change(ptr);
obj.print();
return 0;
}
錯誤:
main.cpp:18:31: error: lvalue required as left operand of assignment
18 | void change(Test *t) { this = t; }
|
我搜索了這個錯誤,發現它通常發生在我們嘗試將賦值運算子左側的常量分配給右側的變數時。如果我錯了,請糾正我。
謝謝
uj5u.com熱心網友回復:


uj5u.com熱心網友回復:
根據9.3.2 this指標[class.this]
1 在非靜態(9.3) 成員函式的主體中,關鍵字
this是一個純右值運算式,其值是呼叫該函式的物件的地址。[...]
因此,正如錯誤所說,左側應該是一個左值,但您給它一個prvalue,因為它change是一個非靜態成員函式,并且在任何非靜態成員函式中,根據上面參考的陳述句,關鍵字this是一個prvalue。因此錯誤。
但是可以修改this指向的物件,如下圖:
#include <iostream>
using namespace std;
class Test
{
private:
int x;
public:
Test(int x = 0) { this->x = x; }
void change(Test *t) { *this = *t; }//THIS WORKS
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj(15);
Test *ptr = new Test (100);
obj.change(ptr);
obj.print();
return 0;
}
請注意,在上面的示例中,我已替換this = t;為
*this = *t;//this time it works because now the left hand side is an lvalue
這次程式可以作業了,因為現在左邊是一個lvalue。
更多解釋
從IBM 的 this 指標檔案,
該this引數有型 Test *const。也就是說,它是一個指向 Test 物件的常量指標。現在,由于它是常量指標,您不能使用this = t;. 因此錯誤。
同樣,從微軟的 this 指標檔案中,
該
this指標總是一個常量指標。它不能被重新分配。
所以這也解釋了你得到的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372822.html
