新建文件 Software/Program/Language/Cpp/类_Const_成员.md
This commit is contained in:
parent
43e6bf5eba
commit
2481470c44
|
@ -0,0 +1,34 @@
|
|||
# 类 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) {}
|
||||
}
|
||||
```
|
Loading…
Reference in New Issue