c++ - 在类构造函数中初始化结构

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

最佳答案

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

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/

相关文章:

c++ - Kinect 骨架 FPS

c++ - 为什么这个 TAD 返回 0.0000 而不是相关函数的结果?

c++ - 从给定图像中在 OpenCV 中绘制一个环

javascript - 我们什么时候可以避免使用构造函数来初始化状态?

c - 不同 header 中的结构相互引用

c - main 之外的函数中的值不会保留在结构中

C# 不能改变返回值?

c++ - VC 2013 与 2015 中的 Lambda 删除器

ios - Swift nsobjecttype 构造函数

c# - 确保类 A 只能由类 B 创建