2

我发现这里很少有讨论运算符重载和在 c++ 中不能重载的运算符等的帖子. :: .* sizeof。但我找不到确切的细节或为什么应该.*避免的原因?你们中很少有人会认为它是重复的,但如果我能获得关于我想要的链接的详细信息,我会非常高兴:)

4

2 回答 2

8

马口中

操作符.(点)原则上可以使用与 -> 相同的技术进行重载。但是,这样做可能会导致有关操作是否用于对象重载.或引用的对象的问题.例如:

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?
}

这个问题可以通过多种方式解决。在标准化时,尚不清楚哪种方式最好。

AFAIU 同样的推理适用于.*

于 2012-08-22T16:23:26.043 回答
1

It is very easy to understand, if you go through the internal mechanism of operator function invocation.

Say a class Complex can have two members; r for the real part and i for the imaginary part. For instance:

Complex C1(10,20),C2(10,2) // we assume there is an already a two argument constructor within class. 

Now if you write C1+C2 as a statement, the compiler tries to find the overloaded version of the + operator on complex numbers. If you overload the + operator, so C1+C2 is internally translated as c1.operator+(c2).

But what would you translate an overloaded . operator as? For instance:

C1.disp()//display content of a complex object 

Now try to come up with an internal representation of C1.operator.(------). Given that this syntax would modify it's own semantic meaning, the result is hopelessly messy. For that reason overloading the . is not allowed.

于 2015-08-26T16:11:46.467 回答