我正在创建一个程序,我正在尝试从名为Tour的类中创建一个名为Member的类的指针。
为了创建指针我喜欢这样:
void Tour::initiateMember()
{
this->sizeOfArrParticipants = 5;
ptr = new Member*[sizeOfArrParticipants];
}
但是当我后来尝试使用ptr varible时,我注意到它没有正确地创建所有字段。成员类有三个字段,两个字符串和一个int,并且创建了两个字符串,但是在调试它时,永远不会创建整数,它说“它不能准备好内存”。
以下是代码的一些简短示例:
class Member
{
public:
Member();
Member(string name, int memberNr, string phoneNr);
~Member();
void setName(string name);
void setPhoneNr(string phoneNr);
void setMemberNr(int memberNr);
private:
string name;
string phoneNr;
int memberNumber;
};
Member::Member()
{
this->name = "Joe Doe";
this->memberNumber = 0;
this->phoneNr = "0";
}
Member::Member(string name, int memberNr, string phoneNr)
{
this->name = name;
this->memberNumber = memberNr;
this->phoneNr = phoneNr;
}
Member::~Member()
{
}
void Member::setName(string name)
{
this->name = name;
}
void Member::setPhoneNr(string phoneNr)
{
this->phoneNr = phoneNr;
}
void Member::setMemberNr(int memberNr)
{
this->memberNumber = memberNr;
}
string Member::getName() const
{
return this->name;
}
string Member::getPhoneNr() const
{
return this->phoneNr;
}
int Member::getMemberNr() const
{
return this->memberNumber;
}
class Tour
{
public:
Tour();
Tour(int date, string name, int eduLevel, int typeOfTour, int participants);
~Tour();
void initiateMember();
void addParticipant(int memberNr, string name, string phoneNr);
private:
int date;
int participants;
int typeOfTour;
Member **ptr;
};
Tour::Tour()
{
this->date = 0;
this->typeOfTour = 0;
this->participants = 0;
this->initiateMember();
}
Tour::Tour(int date, string name, int eduLevel, const int typeOfTour, int participants)
{
this->date = date;
this->typeOfTour = 0;
this->participants = participants;
this->initiateMember();
}
Tour::~Tour()
{
}
void Tour::initiateMember()
{
this->sizeOfArrParticipants = 5;
ptr = new Member*[sizeOfArrParticipants];
Member ptr2;
ptr2 = Member::Member();
Member obj1;
obj1.setMemberNr(1);
}
void Tour::addParticipant(int memberNr, string name, string phoneNr)
{
ptr[0]->setMemberNr(memberNr);
ptr[0]->setName(name);
ptr[0]->setPhoneNr(phoneNr);
}
int main()
{
Tour tourB();
tourA.addParticipant(1111, "Stina Larsson", "011-111111");
return 0;
}
现在,当我一直在尝试更多注意到它可行时如果我使用默认构造函数来创建Member类的对象。
Member ptr2;
ptr2 = Member::Member();
然后创建并访问所有字段,为什么我不能使用指针数组执行此操作?