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

猜你喜欢

转载自www.cnblogs.com/esrevinud/p/11993410.html