在类构造函数中初始化结构
Initialize struct in class constructor
如何在类的构造函数中初始化结构指针?例子:
struct my_struct{
int i;
char* name;
};
class my_class{
my_struct* s1;
my_class() {
// here i want to make s1->i = 10; and s1->name = "anyname" ;
// should i assign it like s1->i= 10; and call new for s1->name and strcpy(s1->name "anyname");
// it compiles in g++ without any warning/error but gives seg fault at run time
}
};
我很惊讶没有人提出以下建议…
struct my_struct
{
int i;
std::string name;
my_struct(int argI, std::string const& argName) : i(argI), name(argName) {}
};
class my_class
{
my_struct s1; // no need for pointers!
my_class() : s1(1, std::string("test name")) {} // construct s1 using the two argument constructor, can also default construct as well.
};
使用这种方法,您不需要担心清理s1
,它是自动的…
创建my_class
实例时,s1
指针不指向任何东西。您必须像这样为它分配内存:
myclass() {
s1 = new my_struct;
// initialize variables
}
你还必须为它创建一个析构函数:
~myclass() {
// delete variables
delete s1;
}
另外,由于这是c++,我建议您使用std::string
而不是char*
s。
由于这是c++,所以使用std::string
代替char*
:
struct my_struct{
int i;
std::string name;
};
class my_class{
my_struct* s1;
my_class() {
s1 = new my_struct;
s1->i = 10;
s1->name = "anyname";
}
};
您的原始代码出现分段错误的原因是您未能为s1
分配内存,也未能为s1->name
分配内存。我用new
修复了前者,用std::string
修复了后者。如果因为某些原因你不能使用std::string
,在你试图使用strcpy
的地方使用strdup
。
最后,不要忘记为my_class
提供一个析构函数,它将删除s1
(如果您选择char*
和strdup
,则将释放s1->name
)。
我很确定您可以使用初始化列表,并直接使用new+init结构体。此外,您不能忘记,当您完成时必须删除指针:
struct my_struct{
int i;
char* name;
};
class my_class{
my_struct* s1;
my_class() : s1(new my_struct) {
s1->i = 2;
s1->name = "Something";
}
~my_class() { delete s1; }
};
同时,确保你使用char*
是有原因的,否则std::string
通常会更好。
如果结构在类中,可以使用结构构造函数:
struct my_struct
{
int i;
std::string name;
my_struct()
{
i = 10;
name = "anyname";
};
};
如果它是全局的,你首先需要创建对象,然后初始化它:
class my_class
{
my_struct * s1;
my_class() : s1(new my_struct())
{
s1->i = 10;
s1->name = "anyname";
}
};
my_class() {
s1 = new (my_struct);
s1->i = 10;
s1->name = (char *) malloc(strlen("anyname"));
s1->name = "anyname";
// here i want to make s1->i = 10; and s1->name = "anyname" ;
// should i assign it like s1->i= 10; and call new for s1->name and strcpy(s1->name "anyname");
// it compiles in g++ without any warning/error but gives seg fault at run time
}
~my_class(){
free(s1->name);
delete s1;
}
相关文章:
- 在C和C++中初始化结构中的数组
- 我们可以用参数化构造函数初始化结构的数组吗?
- 尝试初始化结构内的联合时出错
- 使用其他成员初始化结构的成员?
- 使用构造函数初始化结构还是在之后设置其值更好?
- 如果不初始化结构中的向量,它会自动为空还是具有随机内存位置的值?
- 如何在另一个结构中初始化结构数组?
- 如何在构造函数中初始化结构体的动态数组?
- 初始化结构中的联合 - c++
- 尝试初始化结构向量时出现编译错误
- 用于初始化结构的 void 指针强制转换
- 初始化结构的两种方式
- 使用用户定义的构造函数初始化C++结构
- 使用初始值设定项列表初始化结构,对于 std::array 失败
- 在 c++ 中初始化结构的指针
- 无序列图会创建一个零初始化结构吗?
- 如何在C++中初始化结构
- C 用结构指针初始化结构
- 在C 中初始化结构数组
- 使用数组聚合初始化结构数组