我在使用c ++初始化扩展结构时遇到了一些问题。
struct Struct1 {
int property1;
}
struct Struct2: Struct1 {
int property2;
}
int main() {
Struct2 struct_var = { 1, 1 };
std::cout << struct_var.property1;
}
如果有人能指出错误,我将不胜感激?
答案 0 :(得分:4)
如果你在初始化程序中传递2 arguments
,那么你需要拥有2 parameters
的构造函数。像这样的东西
#include <iostream>
struct Struct1 {
int property1;
};
struct Struct2 : Struct1 {
public:
Struct2(int property1, int property2)
{
// Struct1::property1 = property1; // this will also work
this->property1 = property1;
this->property2 = property2;
}
int property2;
};
int main() {
Struct2 struct_var = { 1, 1 };
std::cout << struct_var.property1;
}