前缀和后缀++重载

whdugh 2013-09-03 08:01:35
#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
...全文
91 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
几夜几页 2013-09-03
  • 打赏
  • 举报
回复
whdugh 2013-09-03
  • 打赏
  • 举报
回复
引用 1 楼 max_min_ 的回复:

 ~Integer(){}    // 这样吧!
我晕了 改成你说的那样~Integer(){}真好了
碼上道 2013-09-03
  • 打赏
  • 举报
回复
引用 3 楼 whdugh 的回复:
[quote=引用 1 楼 max_min_ 的回复:]

 ~Integer(){}    // 这样吧!
~Integer();这个编译器自动加的格式 应该没有错吧[/quote] 你的没有函数体,当然是有问题的。需要加上{}
whdugh 2013-09-03
  • 打赏
  • 举报
回复
引用 1 楼 max_min_ 的回复:

 ~Integer(){}    // 这样吧!
~Integer();这个编译器自动加的格式 应该没有错吧
大尾巴猫 2013-09-03
  • 打赏
  • 举报
回复
逻辑上没错 前++完成 内部变量++的功能 后++先保存一个当前值,调用前++,返回临时变量。 后++可以不调用前++,自己完成,改一下就行
Integer Integer::operator++(int)
{
    cout << "Integer::operator(int) called." << endl;
 
    Integer temp = *this;
    //++(*this); //改成下面的
    ++a;
    return temp; //返回this对象的旧值
 
}
max_min_ 2013-09-03
  • 打赏
  • 举报
回复

 ~Integer(){}    // 这样吧!

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧