gpt4 book ai didi

c++ - 成员函数如何传递 "this"指针

转载 作者:行者123 更新时间:2023-11-30 04:08:15 47 4
gpt4 key购买 nike

假设我有一个 Foo 类,它有一个返回非常量引用的成员函数,它本身运行一个使用 const this 指针的成员函数:

class Foo{
public:
Foo& display(std::ostream& os) { do_display(os); return *this; }
private:
void do_display(std::ostream& os) const { os << contents; }
std::string contents;
}

display 运行 do_display 时,this 指针隐式转换为指向 const 的指针。那么,为什么当 do_display 终止时,display 仍然能够更改调用它的对象?据我所知,通常不可能将指向 const 的指针分配给指向非常量的指针。感谢任何见解。

最佳答案

转换 display 中的非常量指针以将其传递给 do_display 创建一个不同类型的新指针;它不会更改现有指针的类型。将 this 传递给成员函数与将参数传递给非成员函数非常相似:

// A non-const member function receives `this` as a non-const pointer
Foo& display(Foo * this, std::ostream & os) {
// Pass a copy of `this`, converted to `Foo const *`
do_display(this, os);

// The local `this` is still `Foo *`
return *this;
}

// A const member function receives `this` as a const pointer
void do_display(Foo const * this, std::ostream & os) {os << this->contents;}

关于c++ - 成员函数如何传递 "this"指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21938304/

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