[英]How do I initialize a dynamically allocated array within a class constructor
we are supposed to assign an empty string into each index and later replace that with a value in the function addB(). 我们应该为每个索引分配一个空字符串,然后在函数addB()中将其替换为一个值。 I am quite new to this so I am having a lot of trouble.
我对此很陌生,所以遇到很多麻烦。
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;}
//...
this is only a snippet of the program showing my issue 这只是显示我的问题的程序的一小段
You should allocate memory before using dynamic array.I have allocated memory for b 您应该在使用动态数组之前分配内存。我已经为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;}
It looks like class A
is supposed to be a dynamic array class. 看起来
class A
应该是动态数组类。
When you create a new instance of A you must also allocate memory for your array b
. 创建A的新实例时,还必须为数组
b
分配内存。 Which is just a pointer to some point in memory. 这只是指向内存中某个点的指针。 From the code you posted, it doesn't get initialized and can point to any random memory place -- which is not good (ie the likely cause of your segfault).
从您发布的代码来看,它不会被初始化,并且可以指向任何随机存储位置-不好(例如,造成段错误的可能原因)。
I'd suggest making the following change. 我建议进行以下更改。
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.
}
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
}
You don't allocate memory for b[i],so you get a segment fault. 您没有为b [i]分配内存,因此会遇到段错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.