关于使用这个指针的问题

Question on using this pointer

本文关键字:问题 指针 于使用      更新时间:2023-10-16

我尝试通过使用类和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;
}

从main中访问这个方法,如下所示:

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;
}

但是它给出了以下错误

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

所有涉及this指针的其他方法都可以正常工作,除了复制部分。我做一些基本错误在使用this指针?

不能覆盖thisthis指针是一个常量,因此不允许更改它。那又意味着什么呢?你不能改变你所在的对象。您可以更改该对象中的值,但不能更改对象本身。

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

同样,你不应该有一个叫做copy的函数;这就是复制构造函数和复制赋值操作符的作用。

不能修改this指针。但是你可以修改*this:

void test::copy(test *temp)
{
    *this = *temp;
}

此外,您应该重命名数据成员或参数,因此您不需要this->:

class test
{
int m_x;
public:
void setx(int x)
{
    m_x = x;
}

test::copy应该做什么?显然,你不能给当前对象分配不同的地址。所以它是无效的。

如果要用其他对象的值初始化当前对象,那么它应该是这样的:

void test::copy(test *temp) {
    this->x = temp->getX();
}