可能重复:
重载运算符 ->
你好,
我已经看到operator->()
它在评估后被链接(重新应用),例如:
struct Bar
{
Bar() : m_str("Hello world!") {}
const string* operator->() const { return &m_str; }
string m_str;
};
struct Foo
{
const Bar& operator->() const { return m_bar; }
Bar m_bar;
};
int main()
{
Foo f;
cout << f->c_str() << endl;
return 0;
}
工作得很好,这需要operator->()
评估三个 -Foo::operator->()
和Bar::operator->()
常规指针解析。
但它不适用于中间的指针 - 如果Foo::operator->()
返回指向 Bar 的指针而不是引用,它将无法编译。例如,同样的情况auto_ptr<auto_ptr<string>>
。
它是否特定于非重载operator->()
,因此它只应用一次并且不会导致链接?是否可以在不使用的情况下使下面的代码工作(*ptr2)-> ...
?
int main()
{
string s = "Hello world";
auto_ptr<string> ptr1(&s);
auto_ptr<auto_ptr<string> > ptr2(&ptr1);
cout << ptr1->c_str() << endl; // fine
cout << ptr2->c_str() << endl; // breaks compilation
}
谢谢!