帮我看看这段c++
[code]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;
}[/code]
我的疑问是const Counter& Counter::operator++() Counter a=++i;返回的应该是1个常量counter对象=a,但为什么后面可以用a.SetItsVal(8);修改a自身的成员变量,还有 return *this;应该是返回i对象,但为什么a和i的内存地址不一样呢,谢谢
还有,Counter a=++i;
写成 Counter &a=++i;
我估计是因为++的返回类型是一个引用类型,但是你定义不是,所以没有用。
具体我也不太清楚,等待高手!
[[it] 本帖最后由 mqh21364 于 2008-6-24 10:14 编辑 [/it]] 你的问题根本和C++无关,是你最基本的东西都没搞懂
对于问题1:
const int a=1;
int b=a;
b=2;
这时候b不能修改吗?初始化b的变量是const的和b有什么关系?
对于问题2:
int a=1;
int b=++a;
请问a和b的地址是一样的吗?显然不一样嘛怎么会认为一样呢 楼上的很正确..........
页:
[1]
