C++構造函數理解

 正確理解Qt中構造函數:Widget::Widget(QWidget *parent) : QWidget(parent),ui(new Ui::Widget)

#include <iostream>

using namespace std;

class Base
{
    public:
        Base():m_num(0){
            cout << "this is Base()" << endl;
        }
        Base(int val):m_num(val + 1){
            cout << "this is Base(int val) and m_num = " << m_num << endl;
        }

    private:
        int m_num;
};

class BaseChild : public Base
{
    public:
        BaseChild(){
            cout << "this is BaseChild()" << endl;
        }
        BaseChild(int val) : Base(val), m_num(val){
            cout << "this is BaseChild(int val) and m_num = " << m_num << endl;
        }

    private:
        int m_num;
};

int main(int argc, char *argv[])
{
    BaseChild child1;
    BaseChild child2(5);

    return 0;
}

輸出結果:

this is Base()
this is BaseChild()
this is Base(int val) and m_num = 6
this is BaseChild(int val) and m_num = 5

BaseChild是類, ::是作用域,::後面的BaseChild(int val)是構造函數,:後面的Base(val)是指定基類的構造函數,不明確指定的話是默認構造函數,n_num(val) 是對BaseChild類裏面的成員變量做初始化。

 

Widget::Widget(QWidget *parent) : QWidget(parent),ui(new Ui::Widget)
理解:
    Widget是類, ::是作用域,::後面的Widget(QWidget *parent)是構造函數,
    :後面的 QWidget(parent)是指定基類的構造函數,不明確指定的話是默認構造函數,
    ui(new Ui::Widget) 是對BaseChild類裏面的成員變量做初始化。

本文借鑑:https://blog.csdn.net/qq_41827665/article/details/84213220

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章