简体   繁体   中英

Why .* operator can not be overloaded in c++?

I found out few of the post here discussing about operator overloading and operators which can not be overloaded in c++ like . :: .* sizeof etc . But I could not find out exact details or reason about why should .* be avoided ? Few of you might vote it as duplicate but I would be more than happy if I get details on those link about what I want :)

From the Horse's mouth :

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

This problem can be solved in several ways. At the time of standardization, it was not obvious which way would be best.

AFAIU the same reasoning applies for .*

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM