请教const,static和const static的问题
请详细解答一下下面的题,本人是菜鸟,越详细越好,谢谢
Fill the blanks inside class definition
Class Test
{
public:
_____ int a;
_____ int b;
public:
Test::Test(int _a, int _b):a(_a)
{
b = _b;
}
};
int Test::b;
int _tmain(int argc, _TCHAR * argv[])
{
Test t1(0, 0), t2(1, 1);
t1.b = 10;
t2.b = 20;
printf("%u %u %u %u", t1.a ,t1.b ,t2.a, t2.b);
return 0;
}
Running result: 0 20 1 20
A. static/const
B. const/static
C. --/static
D.const static/static
E. None of the above
Answer:BC
[解决办法]
Class Test
{
public:
_____ int a;
_____ int b;
public:
Test::Test(int _a, int _b):a(_a)
{
// a通过初始化列表赋值,而且值再未发生变化,所以a可能是const的,也可能不是。
b = _b;
}
};
int Test::b; // b在类外定义,通过类名引用,b一定是static的。
// a没有如此在类外定义,a一定不是static的。
int _tmain(int argc, _TCHAR * argv[])
{
Test t1(0, 0), t2(1, 1);
t1.b = 10;
t2.b = 20;
printf("%u %u %u %u", t1.a ,t1.b ,t2.a, t2.b);
return 0;
}
// Running result: 0 20 1 20
[解决办法]
能够判断的就是b的值,
注意到t1.b的值随着t2.b的值一起更改了。
所以能够判断它是static的,
static是被该类所有对象共享的变量。
至于a的修饰const或者为空都是可以的
如果a是const修饰的话,a的初始化只能像下面的代码一样了。
如果也放在跟b一起的位置是会报错的
Test::Test(int _a, int _b):a(_a)
{
b = _b;
}
可能说的不清楚,不过我的理解就是这样
[解决办法]
因为结果b都是20,对b的最后一次赋值就是赋得20,符合static变量,对于static变量你要记住两点1所有的对象拥有共同的static变量,2static变量的初始化应在类外,并且形式为 类型名 类名::变量名
对于类中的const变量在构造函数中的初始化必须要用初始化列表的形式,对于一般的变量则可以用初始化列表的形式,也可以不使用初始化列表的形式,所以答案是BC