【发布时间】:2019-05-22 04:06:10
【问题描述】:
我一直在尝试理解运算符重载,但没有在以下程序中使用返回类型作为类类型: 当我用“int”切换“重载”返回类型时,它工作正常。
#include <iostream>
using namespace std;
class overload {
private:
int count;
public:
overload(int i)
: count(i)
{
}
overload operator++(int) //why return type is class type when i can use int
{
return (count++);
}
overload operator++() //why return type is class type when i can use int
{
count = count + 1;
return count;
}
void Display()
{
cout << "Count: " << count<<endl;
}
};
// Driver code
int main()
{
overload i(5);
overload post(5);
overload pre(5);
// this calls "function overload operator ++()" function
pre = ++i;
post = i++;
i.Display();
return 0;
}
【问题讨论】:
-
你想要它为什么工作/不工作,解释还是你只是想要让它正常工作的答案?
-
它可以是
int,但重载运算符的正常做法是按照人们期望的某种方式表现(返回与操作数相同的类型,并且返回正确的值类别为 pre -增量)。