在类构造函数中初始化结构

Initialize struct in class constructor

本文关键字:初始化 结构 构造函数      更新时间:2023-10-16

如何在类的构造函数中初始化结构指针?例子:

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;
  }