如何在 class 构造函数中初始化动态分配的数组

How do I initialize a dynamically allocated array within a class constructor

我们应该为每个索引分配一个空字符串,然后替换 在函数 addB() 中有一个值。 我对此很陌生,所以遇到了很多麻烦。

class A //in a.h

{

  private:

    B * b;

    int maxNumberOfItems;

    //...

  public:

  A();

  ~A();

 void addB(const B & something);

};

//in a.cpp

 A::A()

  {

    maxNumberOfItems=10;
    for(int i=0;i<maxNumberOfItems;i++)
    {
       b[i]="";//has to be an empty string, I am getting a segmentation fault
    }

  }

  A::~A(){/*...*/}

  //...

//in b.h

class B
{

 private:

      string name;

      int price;

  public:

      void setName(string);

      string getName();

      void setPrice();

      int getPrice(int);

      B & operator=(string &);

};

//in b.cpp

B & B::operator=(string & a){name = a;price = 0; return *this;}
//...

这只是显示我的问题的程序片段

maxNumberOfItems=10;
//add this line to your code
b = new B[maxNumberOfItems];
//do some error check stuff
for(int i=0;i<maxNumberOfItems;i++)
{
   b[i]="";//has to be an empty string, I am getting a segmentation fault
}

你没有为 b[i] 分配内存,所以你得到一个段错误。

你应该在使用动态之前分配内存 array.I 已经为 b

分配了内存
class A //in a.h

{

private:

    B * b;

    int maxNumberOfItems;

    //...

public:

A();

~A();

void addB(const B & something);

};

//in a.cpp

A::A()

{
    maxNumberOfItems=10;
    b = new B[maxNumberOfItems];

    for(int i=0;i<maxNumberOfItems;i++)
    {
    b[i]="";//has to be an empty string, I am getting a segmentation fault
    }

}

A::~A(){/*...*/}

//...

//in b.h

class B
{

private:

    string name;

    int price;

public:

    void setName(string);

    string getName();

    void setPrice();

    int getPrice(int);

    B & operator=(string &);

};

//in b.cpp

B & B::operator=(string & a){name = a;price = 0; return *this;}

看起来 class A 应该是一个动态数组 class。

创建 A 的新实例时,还必须为数组分配内存 b。这只是指向内存中某个点的指针。从您发布的代码来看,它没有被初始化并且可以指向任何随机内存位置——这不好(即您的段错误的可能原因)。

我建议进行以下更改。

A::A(){
  maxNumberOfItems=10;
  b = new B[maxNumberOfItems]; // b is an array of B objects.
                               // with default constructed values
  // This way avoids the need for using a for loop and reassigning values
}

~A(){
  if (b != NULL) { delete b; }
}

class B{
  private:
    //....
  public:
     B(): name(""), price(0) {}
    // Although the default constructor without defining one should behave the same.
    // This just makes it explicit. what name and price default to.
}