1

I am trying to make a custom type in C++

I am trying to overload the + operator

class MyClass {
  ....
  int operator+(int i) {
    ....
  }
}

That works with

int main() {
  MyClass MC;
  count << MC+1;
}

How can I get it to work with 1+MC

Vbrawl
  • 77
  • 4
  • Define the operator at namespace scope (possibly as friend operator defined inside the class itself should you need access to private members). `int operator+(int i, MyClass const& c) { ... }` which could even be implemented using the member operator, assuming you make it `const`... – fabian Sep 30 '21 at 18:53

1 Answers1

1

This is what I did.

^ cat Foo.cpp
#include <iostream>

class MyClass {
public:
    int value = 5;
};

int operator+(const int value1, const MyClass &value2) { return value1 + value2.value; }

int main() {
    MyClass myClass;
    int newValue = 1 + myClass;

    std::cout << newValue << std::endl;
}

^ make Foo
g++     Foo.cpp   -o Foo
^ Foo
6

You'll see that I made a free function for it.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36