帮我看看这段c++

pengxuan1 2008-06-24 10:07:12
typedef unsigned short USHORT;
#include <iostream.h>

class Counter
{
public:
Counter();
~Counter(){}
USHORT GetItsVal()const { return itsVal; }
void SetItsVal(USHORT x) {itsVal = x; }
void Increment() { ++itsVal; }
const Counter& operator++ ();

private:
USHORT itsVal;

};

Counter::Counter():
itsVal(0)
{};

const Counter& Counter::operator++()
{
++itsVal;
cout<<this<<endl;

return *this;
}

int main()
{
Counter i;
cout << "The value of i is " << i.GetItsVal() << endl;
i.Increment();
cout << "The value of i is " << i.GetItsVal() << endl;
++i;
cout<<&i<<endl;
cout << "The value of i is " << i.GetItsVal() << endl;
Counter a=++i;
cout<<&a<<endl;
cout<<&i<<endl;
a.SetItsVal(8);
cout << "The value of a: " << a.GetItsVal();

cout << " and i: " << i.GetItsVal() << endl;
return 0;
}
我的疑问是const Counter& Counter::operator++() Counter a=++i;返回的应该是1个常量counter对象=a,但为什么后面可以用a.SetItsVal(8);修改a自身的成员变量,还有 return *this;应该是返回i对象,但为什么a和i的内存地址不一样呢,谢谢
...全文
111 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cross2 2008-06-24
  • 打赏
  • 举报
回复
xkyx_cn 2008-06-24
  • 打赏
  • 举报
回复
Counter a=++i;
operator++是返回的const Counter&,但并不是返回给a,
而是返回给拷贝构造函数,你这里并未提供,但编译器会生成一个默认的
形式如下:
Counter(const Counter& other);
用这个函数来构造a

如此一来,a和i便是2个不同的对象,修改a顺理成章,它们的地址也不会相同

babyvox1999 2008-06-24
  • 打赏
  • 举报
回复
返回的是常量只是说明不能作为左值去修改,赋值给a后,a不是常量;返回的是对象所以是深拷贝,当然地址不一样

33,319

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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