我们如何在类的构造函数中初始化结构指针。 示例:
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
,它是自动的...
关于c++ - 在类构造函数中初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7510967/