建構函式初始化列表
阿新 • • 發佈:2020-09-01
通過建構函式初始化引數,可能經常會這麼幹:
class TEST { private: /* data */ public: TEST(int abc,int bcd,int fds); ~TEST(); public: int abc; int bcd; int fds; }; TEST::TEST(int abc,int bcd,int fds) { this->abc = abc; this->bcd = bcd; this->fds = fds; } TEST::~TEST() { }
為了簡化這種寫法,我們採用初始化列表
class TEST { private: /* data */ public: TEST(int a,int b,int c); ~TEST(); public: int abc; int bcd; int fds; }; TEST::TEST(int a,int b,int c):abc(a),bcd(b),fds(c) { } TEST::~TEST() { }
和上面的寫法作用相同,都是把區域性變數的值傳給test的成員變數
也可以不寫引數,直接給他賦值
class TEST {private: /* data */ public: TEST(); ~TEST(); public: int abc; int bcd; int fds; }; TEST::TEST():abc(5),bcd(6),fds(7) { } TEST::~TEST() { }
這樣在使用TEST的時候他們的值 直接就是 5 6 7
測試:
#include <iostream> #include <stdio.h> using namespace std; class TEST { private: /* data */ public: TEST(); ~TEST(); void p_printf(); public: int abc; int bcd; int fds; }; TEST::TEST():abc(5),bcd(6),fds(7) { } TEST::~TEST() { } void TEST::p_printf() { printf("---%d---\n",this->abc); printf("---%d---\n",this->bcd); printf("---%d---\n",this->fds); } int main(int argc, char const *argv[]) { TEST test; test.p_printf(); return 0; }
輸出:
---5--- ---6--- ---7---
初始化 const 成員變數的唯一方法就是使用初始化列表
假設上面例子中的成員都是const修飾的
class TEST { private: /* data */ public: TEST(int a,int b,int c); ~TEST(); void p_printf(); public: const int abc; const int fds; const int bcd; }; TEST::TEST(int a,int b,int c) { this->abc = a; this->bcd = b; this->fds = c; } TEST::~TEST() { }
這樣初始化是不會成功的
報錯如下
test.cpp: In constructor ‘TEST::TEST(int, int, int)’: test.cpp:23:1: error: uninitialized const member in ‘const int’ [-fpermissive] TEST::TEST(int a,int b,int c) ^ test.cpp:18:12: note: ‘const int TEST::abc’ should be initialized const int abc; ^ test.cpp:23:1: error: uninitialized const member in ‘const int’ [-fpermissive] TEST::TEST(int a,int b,int c) ^ test.cpp:19:12: note: ‘const int TEST::fds’ should be initialized const int fds; ^ test.cpp:23:1: error: uninitialized const member in ‘const int’ [-fpermissive] TEST::TEST(int a,int b,int c) ^ test.cpp:20:12: note: ‘const int TEST::bcd’ should be initialized const int bcd; ^ test.cpp:25:12: error: assignment of read-only member ‘TEST::abc’ this->abc = a; ^ test.cpp:26:12: error: assignment of read-only member ‘TEST::bcd’ this->bcd = b; ^ test.cpp:27:12: error: assignment of read-only member ‘TEST::fds’ this->fds = c; ^
這個時候只能選擇用初始化例表的方式初始化const修飾的成員變數
class TEST { private: /* data */ public: TEST(int a,int b,int c); ~TEST(); void p_printf(); public: const int abc; const int fds; const int bcd; }; TEST::TEST(int a,int b,int c):abc(a),bcd(b),fds(c) { } TEST::~TEST() { }