*" and ".*"."/> *" and ".*".">

Home  >  Article  >  Backend Development  >  Which C++ operators cannot be overloaded?

Which C++ operators cannot be overloaded?

青灯夜游
青灯夜游Original
2020-12-21 15:20:1514272browse

C Operators that cannot be overloaded include: 1. Conditional operator "?:"; 2. Member access operator "."; 3. Domain operator "::"; 4. Length operation operator "sizeof"; 5. Member pointer access operators "->*" and ".*".

Which C++ operators cannot be overloaded?

Related recommendations: "C Video Tutorial"

Overloading: Allow operators to have new semantics, Rather than changing the syntax, which would cause confusion.

Part of the rules for overloading: At least one parameter of the operation function must be an object of the class or a reference to the object of the class.

There are 5 operators that cannot be overloaded in C, which are:

  • "?:" (conditional operator)

  • "."(member access operator)

  • "::"(field operator)

  • "sizeof" (Length operator)

  • "->*" and ".*" (Member pointer access operator)

Then these Why can't operators be overloaded? Reason introduction:

(1)“?:”

Assuming it can be overloaded, then let’s look at the following code:

exp1 ? exp2 : exp3

The meaning of this operator is to execute one of exp2 and exp3. If it is overloaded, there is no guarantee that one, two, or neither will be executed. The jump property of this operator will no longer exist. . Therefore, "?:" cannot be overloaded.

(2)"."

Assuming that it can be overloaded, we can assume a situation, create an object, and call the object's function.

class Y{
   public:
      void fun();
};
class X{
   public:
      Y* p;
      Y& operator.(){
          return *p;
      }
      void fun();
}
void g(X& x){
      x.fun();
}

In this example, x.fun() does not know which fun function is called.
The meaning of the "." operator is to reference object members, but this is no longer guaranteed after being overloaded, leading to confusion about the meaning of the operator.

(3)“::”

This operator is only domain parsed during compilation and does not participate in operations. According to the overloading rules, if the operator is overloaded, new semantics are given and confusion may occur.

(4)"sizeof"

The reason why it cannot be overloaded is mainly that many internal pointers rely on sizeof.

(5)"->*" and ".*"

reference pointer to class member

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Which C++ operators cannot be overloaded?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn