gpt4 book ai didi

c++ - 将对象的 'this'指针更改为指向不同的对象

转载 作者:IT老高 更新时间:2023-10-28 21:34:50 24 4
gpt4 key购买 nike

class C{
//methods and properties
}

void C::some_method(C* b){
delete this;
this = b;
}

编译时出现以下错误:

error: lvalue required as left operand of assignment

我的意图:假设有 C 类的对象 a 和 b。C 类的内容可能非常庞大,逐个字段的复制可能非常昂贵。我希望以经济的方式将 'a' 的所有内容替换为 'b'。

默认的复制构造函数会完成预期的任务吗?

我发现了一个叫做“移动构造函数”的东西 http://akrzemi1.wordpress.com/2011/08/11/move-constructor/

也许,它可能会得到我想要的效果。

最佳答案

this 指针是一个隐式指针,指向您正在其上下文中工作的对象,您不能重新分配它。

根据 Stroustrup 的圣经(The C++ Programming Language, 3rd edition I have)this 表示为

C * const this

意味着你有一个指向你的类C常量指针,所以如果你试图改变它,编译器会报错。

编辑:

正如我更正的那样,上面提到的表达式没有完全正确地描述 this,因为 this 实际上是一个右值。

关于c++ - 将对象的 'this'指针更改为指向不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com