在C++中初始化扩展结构
问题描述:
我在初始化C++中的扩展结构时遇到了一些问题。在C++中初始化扩展结构
struct Struct1 {
int property1;
}
struct Struct2: Struct1 {
int property2;
}
int main() {
Struct2 struct_var = { 1, 1 };
std::cout << struct_var.property1;
}
如果有人能指出什么是错的,我将不胜感激?
答
如果您在初始化程序中通过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;
}
Struct2不是聚合,不能用聚合初始化进行初始化。 – 2015-04-02 06:40:37
那么我如何初始化Struct2?我认为它继承了Struct1的一切,你可以做一个'{..}'? – einstein 2015-04-02 06:43:31
好 - 就算是'爱因斯坦'也不知道! – billz 2015-04-02 06:45:10