之前不知道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