简体   繁体   中英

C++ operator overloading not possible with **

Suppose I have a class called Complex, why I'm allowed to define the following function:

Complex operator+(Complex& c1, Complex& c2);

But I can't write:

Complex operator**(Complex& c1, Complex& c2);//for power

** is not a valid C++ operator on its own, it is simply two * operators with no whitespace. We cannot create new operators in C++, but operator* can be overloaded as an unary or a binary operator. operator* can be implemented as a non-member function, member function, or friend function, depending on the class structure. Below is an example of operator* implemented as a binary, non-member function, which returns a new Example object.

struct Example {
    int x;
};

Example operator*(Example a, const Example& b){
    return a *= b;
}

From over.oper , you can see which operators can be overloaded. You will notice that ** is not one of the valid operators to overload. There is, however, the ^ operator you can use (although it's usually meant for bitwise)

As mentioned in the comments, you cannot create new operators this way, so you cannot make a new one for **

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