1.初始化列表的格式
Test() :ci(10) { }
#include <stdio.h>
class Test {
private:
const int ci;
public:
Test() :ci(10) {
}
int getCI() {
return ci;
}
};
int main() {
Test t;
printf("t.ci=%d\n", t.getCI()); //10
return 0;
}
2.注意事项:
(1)成员的初始化顺序与成员的声明顺序相同
(2)成员的初始化顺序与初始化列表中的位置无关
(3)初始化列表先于构造函数的函数体执行
#include <stdio.h>
class Value {
private:
int mi = 0;//不能在这边进行初始化,只能使用初始化列表
public:
Value(int i) {
printf("i=%d\n", i);
mi = i;
}
int getI() {
return mi;
}
};
class Test {
private:
//Value m2(1);报错,因为编译器会误解为 "函数声明",在main函数中可以用这种初始化方法
Value m2;
Value m3;
Value m1;
public:
Test():m1(1),m2(2),m3(3){
printf("Test::Test()\n");
}
};
int main() {
Test t; //i=2,i=3,i=1 Test::Test()
return 0;
}
3.类中的const成员
(1)类中的const成员会被分配空间,如果当前对象在栈上分配空间,则cons成员也在栈上,如果在堆中分配空间,则const成员也在堆上
(2)类中的const成员的本质是只读变量
(3)类中的const成员只能在初始化列表中指定初始值
#include <stdio.h>
class Value {
private:
int mi = 0;//不能在这边进行初始化,只能使用初始化列表
public:
Value(int i) {
printf("i=%d\n", i);
mi = i;
}
int getI() {
return mi;
}
};
class Test {
private:
//Value m2(1);报错,因为编译器会误解为 "函数声明",在main函数中可以用这种初始化方法
const int ci;
Value m2;
Value m3;
Value m1;
public:
Test():m1(1),m2(2),m3(3),ci(100){
printf("Test::Test()\n");
}
int getCI() {
return ci;
}
void setCI(int v) {
int* p = const_cast<int*>(&ci);
*p = v;
}
};
int main() {
Test t;
printf("t.ci=%d\n", t.getCI());
t.setCI(10);
printf("t.ci=%d\n", t.getCI());
return 0;
}
运行结果:
