我在研究重载 ->
操作符。 我想出了以下简单示例:
struct foo
{
int p = 12;
};
struct A
{
foo* f;
A()
{
this->f = new foo();
}
foo* operator-> ()
{
return f;
}
};
int main()
{
A a;
std::cout << a->p; //output 12
}
虽然这个例子可以运行,但我希望有人能告诉我它为什么能够运行。 我曾认为它应该像这样工作
std::cout << a->->p; //The first arrow returns the pointer
//the second arrow dereferences it
但在这里似乎单个箭头不仅返回指针,而且还对其进行解引用。这是C ++中的特殊情况吗?
operator->
不能返回引用。智能指针只会返回引用而不是指针。(实际上,对我来说不清楚为什么operator->
不能隐式地通过一元运算符operator*
来实现。) - cdhowie