中初始化一個動態分配的數組,我們應該爲每個索引分配一個空字符串,並用函數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;}
//...
這只是一個顯示我的問題
'b'似乎是一個未初始化的指針......你想知道_how_分配內存嗎? –
你的'b'沒有被分配。閱讀關於[operator new \ [\]](http://en.cppreference.com/w/cpp/memory/new/operator_new) –
房間裏的大象:使用'std :: vector'而不是動態數組,如果可能的話。 – user4581301