关于使用这个指针的问题
Question on using this pointer
我尝试通过使用类和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
指针?
不能覆盖this
。this
指针是一个常量,因此不允许更改它。那又意味着什么呢?你不能改变你所在的对象。您可以更改该对象中的值,但不能更改对象本身。
您需要按值(按对象中存储的内容)复制其他对象,而不是按指针。
同样,你不应该有一个叫做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();
}
相关文章:
- 关于 c++ 函数中指针赋值的简单问题
- 链表指针问题
- C++ 关于指针取消引用的技术问题
- C++中的指针和常量问题不大
- 包含矢量指针的结构的内存释放问题
- 指针问题:从不兼容的类型"int"分配给"int *"
- 将字节数组转换为带有字节序问题的指针
- 关于如何使用指向主窗口的指针的 QT 问题
- 当成员值从指针更改为非指针时,C++常量问题
- 为什么循环会导致指针出现问题?
- 使用指针计算堆栈问题的大 O 表示法
- 构造函数 (C++) 中的 char 指针参数存在问题
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- 涉及指针和手动实现的矩阵类的问题
- 从基指针到派生的强制转换问题
- 迭代器的指针操作问题
- 64 位迁移问题:指针更改
- C++模板使用问题指针
- 跳到C++第13章练习问题4-指针
- 用std::pair数组初始化std::map问题(指针错误?)