diff --git a/Software/Program/Language/Cpp/类_Const_成员.md b/Software/Program/Language/Cpp/类_Const_成员.md new file mode 100644 index 0000000..dcecf1d --- /dev/null +++ b/Software/Program/Language/Cpp/类_Const_成员.md @@ -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) {} +} +```