【发布时间】:2011-06-22 20:04:45
【问题描述】:
嗨,
我看到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
}
谢谢!
【问题讨论】:
-
重复Overloading operator -> [AndreyT 的回答解释了
operator->的行为以及“链接”是如何发生的。] -
@James 我倾向于保持开放,因为问题的措辞不同。它可以帮助其他人找到答案。
-
@Judge:一个封闭的问题不会被自动删除,像这样一个问得很好的问题也不会被删除;该问题仍然存在并且可以搜索。
-
谢谢!然后似乎无法覆盖 operator-> for 指针,因此第二个问题无能为力。对吗?
-
需要注意的是,这种方式使用
auto_ptr会导致函数结束时销毁变量时发生各种可怕的事情。
标签: c++ operator-keyword method-chaining