[問題] class 執行順序問題

看板C_and_CPP作者 (hinamatsuri)時間6年前 (2018/05/22 20:08), 編輯推噓0(002)
留言2則, 2人參與, 6年前最新討論串1/1
#include <iostream> using namespace std; class Base { public: Base(int i) : m_j(i), m_i(m_j) {} Base() : m_j(0), m_i(m_j) {} int get_i() const { return m_i; } int get_j() const { return m_j; } private: int m_i; int m_j; }; int main() { Base obj(98); cout << obj.get_i() << endl << obj.get_j() << endl; return 0; } 程式初學者,想請問 1.int m_i; int m_j; 這個2個變數定義在下面,可是上面函式卻先使用了,為什麼不會發生錯誤呢? 2.Base() : m_j(0), m_i(m_j) {} 執行這一行的時候不會讓m_j變為0嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.110.76.190 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1526990888.A.46C.html

05/22 20:31, 6年前 , 1F
你呼叫的是Base(int)
05/22 20:31, 1F

05/23 11:57, 6年前 , 2F
初始化列表的順序要跟data member宣告順序一致
05/23 11:57, 2F
文章代碼(AID): #1R10WeHi (C_and_CPP)