C++ multiple operator overloads for the same operator

前端 未结 3 1938
星月不相逢
星月不相逢 2021-02-14 04:14

I know I can answer this question easily for myself by generatin the code and see if it compiles. But since I couldn\'t find a similar question, I thought it\'s knowledge worth

3条回答
  •  没有蜡笔的小新
    2021-02-14 05:01

    Yes, you can overload operators like this. But I'm not sure what "switch case" you are referring to. You can live with one overload if you have a converting constructor

    class MyClass{
    ...
    // code for creating a MyClass out of an int
    MyClass(int n) { ... }
    ...
    inline const MyClass MyClass::operator+(const MyClass &addend) const {
        cout<<"Adding MyClass+MyClass"<

    No switch is needed at all. This is eligible if "MyClass" logically represents a number.

    Notice that you should overload these operators by non-member functions. In your code 5 + c1 would not work, because there is no operator that takes an int as left hand side. The following would work

    inline const MyClass operator+(const MyClass &lhs, const MyClass &rhs) {
      // ...
    }
    

    Now if you keep the converting constructor you can add the int by either side with minimal code overhead.

提交回复
热议问题