i 应该返回 ob this 的地址,但它返回 i,有什么解释吗? #include using namespace std; class myclass { public: int i-6ren">
gpt4 book ai didi

c++ - ob->i 应该返回 ob "this"的地址,但它返回 i ,任何解释?

转载 作者:搜寻专家 更新时间:2023-10-30 23:52:22 26 4
gpt4 key购买 nike

ob->i 应该返回 ob this 的地址,但它返回 i,有什么解释吗?

#include <iostream>
using namespace std;

class myclass {
public:
int i;

myclass *operator->() {return this;}
};

int main() {
myclass ob;
ob.i = 10;

cout << ob.i << " " << ob->i;
// ob->i supposed to return the address of ob "this" but it returns i

return 0;
}

最佳答案

返回i在这里是有道理的。你的电话相当于说 this->ithis是您的箭头运算符返回的内容。换句话说,您正在取消引用 this ,并使用它来访问变量 i在你的课上。要获取对象的地址,您必须使用一元 &对象上的(引用)运算符,即(std::cout << &obj << "\n")

关于c++ - ob->i 应该返回 ob "this"的地址,但它返回 i ,任何解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599171/

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