为什么你不能超载'。运算符在C ++? [英] Why can't you overload the '.' operator in C++?

查看:186
本文介绍了为什么你不能超载'。运算符在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将是非常有用的能够重载。

It would be very useful to be able to overload the . operator in C++ and return a reference to an object.

您可以重载 operator-> 运算符* 但不是运算符。

这?

推荐答案

请参阅此报价来自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?
}

这个问题可以通过几种方式解决。在
标准化的时候,并不明显哪种方式是最好的。有关更多
的详情,请参见 C ++的设计和演变

This problem can be solved in several ways. At the time of standardization, it was not obvious which way would be best. For more details, see The Design and Evolution of C++.

这篇关于为什么你不能超载'。运算符在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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