我们应该为每个索引分配一个空字符串,然后在函数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分配了内存
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;}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句