要求:书名、作者、出版社可以用字符数组保存,单价用float型变量保存,由于简介大小不确定,因此需要使用字符指针动态申请内存。需要提供构造函数、析构函数、获取简介函数和获取书名函数。编写主函数对Book类进行测试。
#include<iostream>
using namespace std;
class Book
{
public:
//构造函数
Book(const char* title, const char* author, const char* publisher,float price,const char*pprofile)//构造函数
{
strcpy_s(m_nTitle, strlen(title) + 1, title);//将书名复制到title数组中
strcpy_s(m_nAuthor, strlen(author) + 1, author);
strcpy_s(m_nPublisher, strlen(publisher) + 1, publisher);
m_nPrice = price;
m_pProfile = new char[strlen(pprofile) + 1];
strcpy_s(m_pProfile, strlen(pprofile) + 1, pprofile);
}
~Book() //析构函数
{
if (m_pProfile != NULL)
{
delete[]m_pProfile;
m_pProfile = NULL;
}
}
const char* getProfile()//获取简介函数
{
return m_pProfile;
}
const char* getTitle()
{
return m_nTitle;
}
private:
char m_nTitle[50];
char m_nAuthor[50];
char m_nPublisher[50];//字符数组
float m_nPrice;
char* m_pProfile=NULL;//字符指针
};
int main()
{
Book book1("《时间简史》", "霍金", "湖南科学技术出版社", 26.10f, "这本书讲述了宇宙的起源、空间和时间以及相对论等内容。");
cout << "书名:" << book1.getTitle() << endl;
cout << "简介:" << book1.getProfile() << endl;
return 0;
}
输出试试:
ok,没有问题!