C ++运算符++重载如何工作

问题描述

我目前正在练习关于增量运算符++的运算符重载,因此我想创建一个仅具有整数m_Int的类myInt并将其初始化为零。为区分前后增量,我创建了两个重载函数,如下所示:

#include <iostream>
#include <string>
using namespace std;

class myInt 
{
    friend ostream & operator<<(ostream &cout,myInt &i);
    friend myInt & operator++(myInt &i);
public:
    myInt() 
    {
        m_Int = 0;
    }
    // post increment
    myInt operator++() 
    {
        myInt temp = *this;
        m_Int++;
        return temp;
    }
private:
    int m_Int;
};

ostream & operator<<(ostream &cout,myInt &i) 
{
    cout << "i.m_Int = " << i.m_Int;
    return cout;
}
// pre increment
myInt & operator++(myInt &i) 
{
    i.m_Int += 1;
    return i;
}
void test() 
{
    myInt int1;
    cout << int1 << endl;       // output ought to be 0 here
    cout << ++int1 << endl;     // having 1 here for prefix increment 
    cout << int1++ << endl;     // still 1 since its postfix increment
    cout << int1 << endl;       // 2 here thanks to postfix increment
}
int main() 
{
    test();
    system("pause");
    return 0;
}

因此,根据我的理解,以上是我的构想,++ int1 ==运算符++(int1)和int1 ++ == int1.operator ++(),所以我选择将一个函数放在类中,将另一个函数放在类中外。但是我遇到一个错误,说多个函数同时匹配了++ int1和int1 ++,但是这两个函数确实具有不同的参数,是因为一个在类内部定义,而另一个没有,所以参数(myInt&i)不能这里有区别吗? 如果我弄错了“ ++ int1 ==运算符++(int1),而int1 ++ == int1.operator ++()”部分,有人知道吗?以及如何解决这个问题才能使其正常工作?非常感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)