C/C++ 結構體 構造函數


之前不知道C語言結構體居然還能寫構造函數,用的時候要么全部賦值要么先定義了再一個個成員的賦值
結構體的構造函數概念和OOP語言的差不多

struct box  {
    int width;
    int height;

    // 括號內是參數,外是需要賦值的成員
    box () :width(10), height(10) {
        printf("no arg\n");
    }

    box (int width) : width(width), height(10) {
        printf("one arg\n");
    }

    box (int width, int height) : width(width), height(height) {
        printf("full arg\n");
    }

};


int main() {
    struct box a{};
    struct box b{10};
    struct box c{10, 20};

    printf("a: %d %d\n", a.width, a.height);
    printf("b: %d %d\n", b.width, b.height);
    printf("c: %d %d", c.width, c.height);

    return 0;
}

打印輸出

no arg
one arg
full arg
a: 10 10
b: 10 10
c: 10 20


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM