无法使点'.'超载. C ++中的运算符 [英] Inability to overload Dot '.' operator in c++
问题描述
我很难理解Stroustrup的解释,即如果运算符重载.",则必须面对什么困难.被允许.
I have hard time understanding the explanation from Stroustrup for what difficulties one must have faced, if operator overloading for '.' was allowed.
请参阅Bjarne Stroustrup的这句话:
See this quote from Bjarne Stroustrup:
操作员. (点)原则上可以使用与->相同的技术来重载.但是,这样做可能会引起有关操作是否用于对象重载的问题.或所指的对象.例如:
Operator . (dot) could in principle be overloaded using the same technique as used for ->. However, doing so can lead to questions about whether an operation is meant for the object overloading . or an object referred to by . For example:
class Y {
public:
void f();
// ...
};
class X { // assume that you can overload .
Y* p;
Y& operator.() { return *p; }
void f();
// ...
};
void g(X& x)
{
x.f(); // X::f or Y::f or error?
}
在上面的示例中,为什么在执行x.f()
时会有任何困惑?
In the above example why should there be any confusion while executing x.f()
?
Y& operator.() { return *p; }
这是我的想法:
- operator.()在x上被调用,因此
Y& operator.()( return *p; }
应该被调用不是很明显和直观吗? - 在返回指向类型为Y的对象的
*p
之后,应最终调用Y::f()
(不是X::f()
)
- operator.() is called on x hence isn't it obvious and intuitive that
Y& operator.()( return *p; }
should be called ? - Upon returning
*p
which points to object of type Y and henceY::f()
should be called finally ( notX::f()
)
我在Stroustup的解释中缺少什么?为什么不是那么简单?
What am i missing in Stroustup's explanation? Why is it not straightforward?
推荐答案
已经取得了一些进展: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf .由于某些技术问题,它将不在C ++ 17中使用,但我希望在C ++ 20中能够看到它.
There has been some progress: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf . Due to some technical problems this won't be in C++17, but I hope to see it for C++20.
这篇关于无法使点'.'超载. C ++中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!