What is the usage of operator in C++?

In C++, the keyword “operator” is used to define or overload operators. Operators are special functions used to perform specific operations within expressions.

The keyword “operator” in C++ is mainly used in two ways:

  1. Definition of class operator overloading functions: By overloading operator functions, one can define custom class types to behave similar to built-in types. For example, one can overload the “+” operator to implement the addition operation between two objects.
class MyClass {
public:
    int value;
    
    MyClass(int val) : value(val) {}

    MyClass operator+(const MyClass& other) {
        MyClass result(value + other.value);
        return result;
    }
};

int main() {
    MyClass a(5);
    MyClass b(10);
    MyClass c = a + b; // 使用重载的"+"操作符进行相加操作
    return 0;
}
  1. Overloaded built-in operators: In C++, it is also possible to overload some built-in operators for performing customized operations between different types. For example, the “<<" operator can be overloaded to achieve output for custom types.
class MyType {
public:
    int value;
    
    MyType(int val) : value(val) {}

    friend std::ostream& operator<<(std::ostream& os, const MyType& obj) {
        os << obj.value;
        return os;
    }
};

int main() {
    MyType obj(5);
    std::cout << obj; // 使用重载的"<<"操作符输出自定义类型的值
    return 0;
}

It is important to note that not all operators in C++ can be overloaded. Only a few specified operators can be overloaded, and there are limitations and regulations for some operators. Specific rules for operator overloading can be found in C++ documentation and tutorials.

bannerAds