64,642
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
class A
{
public:
A()
{
i = 0;
}
A& operator++();
A& operator++(int i);
friend std::ostream& operator<<(std::ostream &os, const A &a);
private:
int i;
};
A& A::operator ++()
{
++i;
return *this;
}
A& A::operator ++(int i)
{
A a(*this);
++this->i;
return a;
}
std::ostream& operator<<(std::ostream &os, const A &a)
{
os << a.i;
return os;
}
int main()
{
A a;
std::cout << a << std::endl;
std::cout << ++a << std::endl;
std::cout << a++ << std::endl; //输出的值未定义
std::cout << a << std::endl;
system("pause");
return 0;
}
//测试
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 1;
//该语句错误error C2106: '=' : left operand must be l-value 因为后置自增返回类型是一个int型,而不是int&,前置自增返回的是int&
i++ = 2;
printf("%d", i);
system("pause");
return 0;
}