Why isn't operator overloading for pointers allowed to work?

后端 未结 9 2035
鱼传尺愫
鱼传尺愫 2020-12-03 14:08

As per the comment under this answer, references were introduced primarily to support operator overloading which quotes Bjarne Stroustrup:

References

相关标签:
9条回答
  • 2020-12-03 15:00

    Why doesn't it work for pointers? Because it's ambiguous. Would

    ostream* operator<<(ostream* s, const char* c);
    

    match

    cout << 'a';
    

    or

    cout << "a";
    

    ?

    Also, you can't use address-of (&) with a temporary. What should this do:

    complex<double> a, b, c;
    cout << a + b * c;
    

    since b * c is a temporary, and the sum is also.

    ?

    0 讨论(0)
  • 2020-12-03 15:04

    Because if it was allowed, then it would not look good, and wouldn't be as intuitive as its with reference.

    Suppose it is allowed, then you would write:

    struct A{};
    A a, *pa, b;
    
    a = pa ;//doesn't look good, also not intuitive. (not real C++)
    

    It doesn't look good, because on left side you've non-pointer, on right side you've pointer. Looks very very weird. Also, since the types don't match, it doesn't look very intuitive as to what exactly its doing. I mean, you're assigning pointer to a non-pointer; what such an assignment is supposed to do? Copying the content of the address pointed to by pointer to the destination (non-pointer) is not very inttuitive.

    On the other hand, as its allowed with reference (the reality, not a supposition):

    a = b; //looks good, intuitive, as now both side is same type
    

    With reference, you've both side same type, its only when b gets passed to operator=() as argument, it is passed by reference (or say by pointer, as references are syntactic sugar of pointers.) to avoid unnecessary copy, which in turn doesn't hinder performance, as it would if it is passed by value.

    It would be also interesting to note that not only b is passed by reference (or pointer underneath), a also gets passed to the function by pointer, because we know in the function, the keyword this is actually a pointer.

    So references were introduced in C++, to make whole thing look good and intuitive for programmers, otherwise they're pointers underneath. In fact, most compilers implement references using pointers (pointer-mechanism) internally.

    0 讨论(0)
  • 2020-12-03 15:05

    Operators can't be overloaded when both types involved are built-in types (like int, float or any kind of pointer). You can overload operator for one class and one primitive type (or you can just use type conversion). For example you can add std::string and const char *.

    0 讨论(0)
提交回复
热议问题