关于使用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;
}
我从 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 指针时犯了一些基本错误吗?
I tried copying a pointer to another by using a method inside the class and the this
pointer as follows. I am giving the entire test code so that it is clear what is going on.
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;
}
And I access this method from the main as follows:
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;
}
However it gives the following error
In member function ‘void test::copy(test*)’:
error: lvalue required as left operand of assignment
All the other method involving the this
pointer works fine except for the copying part. Am i doing some elementary mistake in using the this
pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法覆盖
此
。this
指针是一个常量,因此您不能更改它。无论如何,这意味着什么?您无法更改所在的对象。您可以更改该对象内的值,但不能更改对象本身。您需要按值(按对象中存储的内容)复制其他对象,而不是按指针。
另外,您不应该有一个名为
copy
的函数;这就是复制构造函数和复制赋值运算符的用途。You cannot overwrite
this
. Thethis
pointer is a constant, so you're not allowed to change it. And what would that mean anyway? You can't change the object that you're in. You can change the values within that object, but not the object itself.You need to copy other objects by value (by what is stored in the object), not by pointer.
Also, you shouldn't have a function called
copy
; that's what copy constructors and copy assignment operators are for.您无法修改
this
指针。不过,您可以修改*this
:此外,您应该重命名数据成员或参数,这样就不需要
this->
:You cannot modify the
this
pointer. You can however modify*this
:Also, you should rename the data member or the parameter, so you don't need
this->
:test::copy 应该做什么?
显然,您不能为当前对象分配不同的地址。所以是无效的。
如果这应该使用其他对象的值初始化当前对象,那么它应该如下所示:
what is test::copy supposed to do?
Clearly you cant assign a different address to your current object. So it is invalid.
if this is supposed to initialize the current object with the values of some other object then it should look like this: