请教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
Test::Test(int _a, int _b):a(_a)
{
b = _b;
}