35 lines
653 B
Markdown
35 lines
653 B
Markdown
|
# 类 Const 成员
|
||
|
|
||
|
类 const 成员为只读变量类型,其初始化需要通过初始化变量列表来完成:
|
||
|
|
||
|
```cpp
|
||
|
class ClassA
|
||
|
{
|
||
|
public:
|
||
|
ClassA():Va(-1), Vb(true) { }
|
||
|
ClassA(int a=-1, bool b=true):Va(a), Vb(b) { }
|
||
|
|
||
|
cont int Va;
|
||
|
const bool Vb;
|
||
|
}
|
||
|
```
|
||
|
|
||
|
如果某子类想要在构造时初始化父类的 const 成员,则需要在子类的初始化列表中调用父类的构造函数:
|
||
|
|
||
|
```cpp
|
||
|
class ClassA
|
||
|
{
|
||
|
public:
|
||
|
ClassA(int a=-1, bool b=true):Va(a), Vb(b) { }
|
||
|
|
||
|
cont int Va;
|
||
|
const bool Vb;
|
||
|
}
|
||
|
|
||
|
class ClassB : public ClassA
|
||
|
{
|
||
|
ClassB():ClassA(1, false) {}
|
||
|
ClassB(int a, bool b):ClassA(a, b) {}
|
||
|
}
|
||
|
```
|