无法使点'.'超载. C ++中的运算符 [英] Inability to overload Dot '.' operator in c++

查看:86
本文介绍了无法使点'.'超载. 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; }

这是我的想法:

  1. operator.()在x上被调用,因此Y& operator.()( return *p; }应该被调用不是很明显和直观吗?
  2. 在返回指向类型为Y的对象的*p之后,应最终调用Y::f()(不是X::f())
  1. operator.() is called on x hence isn't it obvious and intuitive that Y& operator.()( return *p; } should be called ?
  2. Upon returning *p which points to object of type Y and hence Y::f() should be called finally ( not X::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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆