c++ pointer assignment operator overload(not just object assignment but pointer assignment)

后端 未结 3 1845
灰色年华
灰色年华 2020-12-12 05:27

Is there a way to overload the pointer assignment operator? e.g. overload pointer assignment operator for class A when

A *x, *y;
x = y;
相关标签:
3条回答
  • 2020-12-12 05:32

    No, because overloaded operators are only considered when at least one argument has a class or enum type. (A pointer to class type is considered a fundamental type and does not count as a "class type" itself.)

    C++ Standard [over.match.oper]/1-2:

    If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause [expr].

    If either operand has a type that is a class or enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator.

    (Though you might instead encourage users of A to use some smart pointer-like class APtr instead of raw pointers to get the desired behavior.)

    0 讨论(0)
  • 2020-12-12 05:42

    No, this is not possible. Pointer types are scalar types, but overloading operators requires a non-scalar parameter. In particular ([over.oper]p6):

    An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

    If you had a binary operator where one parameter was a user-defined type and the other a pointer, that would work, but in the situation you're asking about, both operands are pointers.

    0 讨论(0)
  • 2020-12-12 05:52

    There is no "pointer assignment operator". This is the assignment operator and you are using it with pointer operands.

    It's not possible to overload an operator unless at least one operand has class or enum type. (Pointer type is not class type).

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