Reputation:
I'm working through some home work and having problems with how to form my method signature for overloading a member of a class.
My header file
class MyInt
{
int internalInt;
public:
MyInt::MyInt(int i);
const MyInt operator+(const MyInt& mi);
const MyInt& operator++();
};
My code file
MyInt::MyInt(int i)
{
internalInt = i;
}
const MyInt MyInt::operator+(const MyInt& mi)
{
cout << "Inside the operator+\n";
mi.print(cout);
return MyInt(internalInt + mi.internalInt);
}
const MyInt& MyInt::operator++()
{
cout << "Inside the operator++\n";
internalInt++;
return this; //Line 42
}
When I try to compile the code I'm getting an error that says
ex4.cpp:42: error: invalid initialization of reference of type ‘const MyInt&’
from expression of type ‘MyInt* const’
I'm having problems understanding how to get this working and have tried a few method signatures. In my text book they are in lining all the overloads but I was hoping to figure out what I'm doing wrong instead of just going with the flow to get my code to compile.
Thanks!
Upvotes: 1
Views: 254
Reputation: 361802
First of all, in operator++()
, write return *this;
instead of return this;
. Also remove the const!
-
const MyInt operator+(const MyInt& mi);
Second, Make it const-function, as
const MyInt MyInt::operator+(const MyInt& mi) const // <--- note this!
This is const-function. Without it, you would not be able to add const objects of MyInt.
After you write const
on the right most side, you can write this:
const MyInt m1(10);
MyInt m2(20);
MyInt m3 = m1 + m2 ; //m1 is const, so it can call ONLY const-function
Upvotes: 2
Reputation: 6981
try:
const MyInt& MyInt::operator++()
{
cout << "Inside the operator++\n";
internalInt++;
return *this;
}
You are returning the this pointer, not the reference, you need to dereference it.
Upvotes: 8