+ 1

Error using header and operator+

As sugested in the course, I'm using a header .h and a .cpp file to each class in the Code Blocks IDE. When I try to put the MyClass operator+(MyClass &obj) in the cpp file this error is showed: /home/marianeg/Documents/cpp/SoloLearn/main.cpp|19|error: no match for ‘operator+’ (operand types are ‘MyClass’ and ‘MyClass’)| When the method is placed in the .h file, it works. How to make it work in the .cpp file? It's good practice use the header file or should I use only use the .cpp one?

30th Jun 2017, 6:00 PM
Mariane Goncalves
Mariane Goncalves - avatar
5 odpowiedzi
+ 7
You were close, In the header file you have a function definition and body, you only need the definition here. In the source File, You have again have a function definition and body, when you require return type (MyClass2) / function (MyClass2::operator+) / body (implementation) See below: Header File: #ifndef MYCLASS2_H #define MYCLASS2_H using namespace std; class MyClass2 { public: int var; MyClass2(); MyClass2(int a); MyClass2 operator+(MyClass2 & obj); }; #endif // MYCLASS2_H SOURCE FILE: #include "Class.h" using namespace std; MyClass2::MyClass2() { } MyClass2::MyClass2(int a) :var(a) { } MyClass2 MyClass2::operator+(MyClass2 &obj) { MyClass2 res; res.var = this->var + obj.var; return res; }
4th Jul 2017, 12:24 AM
jay
jay - avatar
+ 6
I will have a look see for you 😊
4th Jul 2017, 12:03 AM
jay
jay - avatar
+ 5
Good practise to use both header and cpp files Might be a silly question, but did you include the .h file in the .cpp file?
30th Jun 2017, 6:04 PM
jay
jay - avatar
+ 1
Hi Jay, the Code::Blocks generate those includes for me. I think there is something wrong with the syntax, and as the course always provide the code in one file, I'm not figuring out what. This is the code that works: HEADER #ifndef MYCLASS2_H #define MYCLASS2_H using namespace std; class MyClass2 { public: int var; MyClass2(); MyClass2(int a); MyClass2 operator+(MyClass2 &obj) { MyClass2 res; res.var = this->var+obj.var; return res; } }; #endif // MYCLASS2_H If I move the operator code to the source file, as the code bellow, it doesn't work: SOURCE #include "MyClass2.h" using namespace std; MyClass2::MyClass2() { } MyClass2::MyClass2(int a):var(a) { } MyClass2::MyClass2 operator+(MyClass2 &obj) { MyClass2 res; res.var = this->var+obj.var; return res; } Thanks!
3rd Jul 2017, 11:22 PM
Mariane Goncalves
Mariane Goncalves - avatar
+ 1
Now it works!! Thanks!
21st Jul 2017, 10:15 PM
Mariane Goncalves
Mariane Goncalves - avatar