前缀和后缀++重载
#include <iostream>
using namespace std;
class Integer
{
public:
Integer(int i): a(i) {}
Integer& operator++(); //前缀返回对象引用
Integer operator++(int); //后缀返回对象
~Integer();
protected:
private:
int a;
};
//前缀--返回左值
Integer& Integer::operator++()
{
cout << "Integer::operator() called." << endl;
a++;
return *this;
}
//注意:后缀需要加int
Integer Integer::operator++(int)
{
cout << "Integer::operator(int) called." << endl;
Integer temp = *this;
++(*this);
return temp; //返回this对象的旧值
}
int main()
{
Integer x = 1;
++x;
x++;
return 0;
}
这个为什么会报错啊?
return tmep-->error:undefined reference to 'Integer::~Integer()'
然后把~Integer();这句注释掉就没有错了,但是输出结果也不对啊
输出结果:
Integer::operator<int> called
Integer::operator<> called
正确输出应该是这样:
Integer::operator<> called
Integer::operator<int> called
[解决办法]
~Integer(){} // 这样吧!
[解决办法]
你的没有函数体,当然是有问题的。需要加上{}