运行程序时,程序崩溃。错误发生在Administrator类的createNewBook()函数中(bk-> create_Newbook();)。我尝试了很多方法从Administrator类调用Book类的create_Newbook()函数,但程序总是崩溃。
class Book{
private:
char bookName[50],bookAuthor[50];
public:
void create_Newbook()
{
cout<<"\nNEW BOOK ENTRY...\n";
cout<<"\n\nEnter The Name of The Book:";
cin>>bookName;
cout<<"\n\nEnter The Author's Name:";
cin>>bookAuthor;
cout<<"\n\n\nBook Created..";
}
};
class Administrator{
private:
Book *bk;
public:
void admin_menu();
void displayStudent(){cout << "Access Student file....." ;}
void displayStaff() {cout << "Access Staff file....." ;}
void displayOutsider() {cout << "Access Outsider file....." ;}
void deleteStudent() {cout << "Access to delete student data.....";}
void deleteStaff() {cout << "Access to delete staff data.....";}
void deleteOutsider() {cout << "Access to delete outsider data.....";}
void createNewBook();
void displayAllbook() {cout << "Access the file display ALL books.....";}
};
void Administrator::createNewBook() {
char choice;
newBook.open("book.data",ios::out|ios::app);
do
{
bk->create_Newbook();
newBook.write((char*)&bk,sizeof(Book));
cout<<"\n\nDo you want to add more record..(y/n?)";
cin>>choice;
}while(choice=='y'||choice=='Y');
newBook.close();
}
答案 0 :(得分:1)
这段代码存在很多问题。
首先:
newBook.open("book.data", ios::out | ios::app);
此行使用名为newBook的对象,该对象尚未在任何地方创建或初始化。
第二
bk->create_Newbook();
您尚未在任何地方初始化bk
。如果它是一个空指针,那么你的程序将崩溃。你缺少构造函数和析构函数。在代码中的某个时刻,您需要创建对象:例如
bk = new Book()
答案 1 :(得分:0)
#include<iostream>
#include<fstream>
using std::cin;
using std::cout;
using std::ios;
using std::fstream;
class Book{
private:
char bookName[50],bookAuthor[50];
public:
void create_Newbook()
{
cout << "\nNEW BOOK ENTRY...\n";
cout << "\n\nEnter The Name of The Book:";
cin >> bookName;
cout << "\n\nEnter The Author's Name:";
cin >> bookAuthor;
cout << "\n\n\nBook Created..";
}
};
class Administrator{
private:
Book *bk;
public:
void admin_menu();
void displayStudent(){cout << "Access Student file....." ;}
void displayStaff() {cout << "Access Staff file....." ;}
void displayOutsider() {cout << "Access Outsider file....." ;}
void deleteStudent() {cout << "Access to delete student data.....";}
void deleteStaff() {cout << "Access to delete staff data.....";}
void deleteOutsider() {cout << "Access to delete outsider data.....";}
void createNewBook();
void displayAllbook() {cout << "Access the file display ALL books.....";}
};
void Administrator::createNewBook() {
char choice;
fstream newBook; //just create newBook
newBook.open("book.data",ios::out|ios::app);
do
{
bk->create_Newbook(); //this will work. No need to create a new Book varible to call a public function
newBook.write((char*)&bk,sizeof(Book));
cout << "\n\nDo you want to add more record..(y/n?)";
cin >> choice;
}while(choice=='y'||choice=='Y');
newBook.close();
}
int main()
{
Administrator var_a;
var_a.createNewBook();
return 0;
}
输出
NEW BOOK ENTRY...
Enter The Name of The Book:abcd
Enter The Author's Name:efgh
Book Created..
如果你有构造函数
会更好