C++运算符重载方法

1 c++ operator-overloading

我正在完成一些家庭作业,并且遇到如何形成我的方法签名以重载类的成员的问题.

我的头文件

class MyInt
{
    int internalInt;
public:
    MyInt::MyInt(int i);
    const MyInt operator+(const MyInt& mi);
    const MyInt& operator++();
};
Run Code Online (Sandbox Code Playgroud)

我的代码文件

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
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译代码时,我收到一个错误

ex4.cpp:42: error: invalid initialization of reference of type ‘const MyInt&’ 
from expression of type ‘MyInt* const’
Run Code Online (Sandbox Code Playgroud)

我在理解如何使其工作并尝试了一些方法签名时遇到了问题.在我的教科书中,他们正在排除所有重载,但我希望弄清楚我做错了什么,而不是仅仅使用流来获取我的代码进行编译.

谢谢!

Mic*_*Mic 8

尝试:

const MyInt& MyInt::operator++()
{
    cout << "Inside the operator++\n";
    internalInt++;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

您将返回此指针,而不是引用,您需要取消引用它.