我每次进入for循环时都会发生奇怪的崩溃,将每个位置初始化为undefined。任何人都可以阐明为什么会这样吗? #包括 #包括 #包括 使用namespace std;
class MyPhoneBook
{
public:
MyPhoneBook(int, string, string, string, string);
MyPhoneBook();
~MyPhoneBook();
void initialise(int, int, string, string, string, string);
bool search(string&, int);
bool find_free_pos();
void add();
void remove();
void display(int);
friend istream& operator >> (istream& in, MyPhoneBook& ph);
friend ostream& operator << (ostream& out, MyPhoneBook& ph);
private:
int *recordid;
int *status; // -1 is no longer at this number, 0 is blocked, 1 is not blocked, 2 is free
string *name, *areacode, *number, *group;
};
int main(int argc, char** argv)
{
cout << "test 1" << endl;
MyPhoneBook *myphbk; // pointer that will point to an object of a MyPhoneBook class
myphbk = new MyPhoneBook[100]; // now its using dynamic memory
cout << "test 2" << endl; //just for testing
int pos = 0;
for(pos = 0; pos < 100; pos++) // initializing everything to undefined, and position to free (position is the second parameter sended in)
{
myphbk[pos].initialise( (pos+1) , 2 , "Undefined" , "Undefined" , "Undefined" , "Undefined");
}
cout << "test 3" << endl; //just for testing
}
return 0;
void MyPhoneBook::initialise(int recordid_,int status_, string name_, string areacode_, string number_, string group_)
{
//now assign them to private member variables
*recordid = recordid_;
*status = status_;
*name = name_;
*areacode = areacode_;
*number = number_;
*group = group_;
//end of assigning
}
有没有人知道为什么我的程序无法到达cout&lt;&lt; “测试3”&lt;&lt; endl部分程序没有崩溃?
答案 0 :(得分:1)
由于你没有粘贴MyPhoneBook
的构造函数,我只能猜测,但问题可能是行
*recordid = recordid_;
*status = status_;
如果您没有在构造函数中为recordid
和status
分配有效地址,例如由
recordid = new int;
status = new int;
您可能希望将这些成员变量声明为简单int
。