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



ob->i应该返回obthis的地址,但它返回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->i因为this是箭头运算符返回的内容。换句话说,您正在取消引用this,并使用它来访问类中的变量i。要获取对象的地址,您必须在对象上使用一元&(引用)运算符,即 (std::cout << &obj << "n")

使用operator->有点棘手。当编译器看到类似于您的ob->i的表达式时,它首先应用myclass::operator->(),如您所料。但这并不处理->之后的i部分,因此编译器然后将->运算符应用于返回的任何调用myclass::operator->()。它一直这样做,直到它得到一个普通的旧指针,然后它知道如何处理i。所以在上面的代码中,ob->i有两个步骤。首先,它调用myclass::operator->()并返回this,其类型为myclass*。现在它有一个普通的指针,所以它使用该指针到达属于obi

这使得编写看起来像普通指针的类成为可能:

struct my_type {
int i;
};
class funky_class {
my_type* operator->() { return &obj; }
private:
my_type obj;
};

现在我可以说

funky_class funky;
funky->i = 3;

最后一行更改funky.obji的值。

在现实世界中,这个例子有点愚蠢;相反,funky_class会持有指向其他对象的指针。这就是为什么你可以写

std::shared_ptr<my_type> my_obj(new my_type);
my_obj->i = 3;

在这里,my_obj::operator->返回一个my_type*,编译器使用该指针获取my_typei成员。

最新更新