有关使用此指针的问题

Adh*_*tha 1 c++ pointers this

我尝试使用类中的方法和this指针将指针复制到另一个指针,如下所示.我给出了完整的测试代码,以便明确发生了什么.

class test  {
private:
    int x;
public:
    void setx(int x);
    int getx(void);
    void copy(test *temp);
};

void test::setx(int x)  {
    this->x = x;
}

int test::getx(void)    {
    return this->x;
}

void test::copy(test *temp) {
    this = temp;
}
Run Code Online (Sandbox Code Playgroud)

我从主要访问此方法如下:

int main()  {
    test a;
    a.setx(4);
    cout << a.getx()<<endl;
    test *b = new test;
    b->setx(4);
    cout << b->getx()<<endl;
    test *c;
    c=b;
    cout << c->getx()<<endl;
    test *d;
    d->copy(b);
    cout << d->getx()<<endl;
}
Run Code Online (Sandbox Code Playgroud)

但是它会出现以下错误

In member function ‘void test::copy(test*)’:
error: lvalue required as left operand of assignment
Run Code Online (Sandbox Code Playgroud)

this除复制部分外,涉及指针的所有其他方法都能正常工作.我在使用this指针时遇到了一些基本错误吗?

Nic*_*las 7

你无法覆盖this.该this指针是一个常数,所以你不能改变它.无论如何,这意味着什么?您无法更改您所在的对象.您可以更改该对象中的值,但不能更改对象本身.

您需要按值(通过存储在对象中的内容)复制其他对象,而不是通过指针.

此外,你不应该有一个函数调用copy; 这就是复制构造函数和复制赋值运算符的用途.