From 2481470c4489f2534a3d019b641f07de7294c04c Mon Sep 17 00:00:00 2001 From: lion187 Date: Wed, 19 Jun 2019 16:01:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=BB=BA=E6=96=87=E4=BB=B6=20Software?= =?UTF-8?q?/Program/Language/Cpp/=E7=B1=BB=5FConst=5F=E6=88=90=E5=91=98.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Program/Language/Cpp/类_Const_成员.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Software/Program/Language/Cpp/类_Const_成员.md 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) {} +} +```