在类构造函数中初始化struct

Ruc*_*chi 2 c++ constructor struct

我们如何在类的构造函数中初始化结构指针.例:

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  
    }
};
Run Code Online (Sandbox Code Playgroud)

Nim*_*Nim 14

我很惊讶没有人提出以下建议......

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.
};
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您无需担心清理s1,它是自动的......