有一个类的定义如下:
class CBook
{
private:
string name;
string author;
double price;
string publisher;
public:
CBook(){name = "无"; author="无"; price = 0.0; publisher = "无";}
CBook(const CBook &); // 拷贝构造函数
CBook(string , string, double, string); // 带参数的构造函数
CBook(char*, char*, double, char*); // 带参数的构造函数
~CBook(); // 析构函数
void SetName(char*); // 设置书名的成员函数
void SetName(string&); // 设置书名的成员函数
void print()const; // 在屏幕上显示书的信息的成员函数
friend ostream & operator<<(ostream& out, const CBook &); // 输出操作符的重载函数
};
按要求完善 CBook 类的定义
(1) 完善 CBook 类的所有成员函数定义。
(2) 其中输出格式要求如下:
书名:
作者:
价格:
出版社:
(3) 析构函数中要求输出如下信息:
a) “书名”对象被析构了!
b) 输出时,上面 a 步骤中要求的书名用对象的 name 属性值替换
(4) 在主函数中验证上述类的功能,要求的主函数如下所示,不允许进行修改:
void main()
{
string n="C++程序设计", a="王涛", pub="苏州大学出版社";
CBook b1;
cout<<b1<<endl;
b1.SetName(n);
b1.print();
b1.SetName("VB");
cout<<b1<<endl;
CBook b2=b1;
cout<<b2<<endl;
CBook b3(n,a,35.0,pub);
cout<<b3<<endl;
CBook *b4=new CBook("VC++", "李国", 45.0, "清华大学出版社");
cout<<*b4<<endl;
delete b4;
}
/*==============================================================================
*学号:
*作业:E18
*功能:按要求完善 CBook 类的定义
(1) 完善 CBook 类的所有成员函数定义。
(2) 其中输出格式要求如下:
书名:
作者:
价格:
出版社:
(3) 析构函数中要求输出如下信息:
a) “书名”对象被析构了!
b) 输出时,上面 a 步骤中要求的书名用对象的 name 属性值替换
(4) 在主函数中验证上述类的功能,要求的主函数如下所示,不允许进行修改
*作者:
*日期:2016.5.17
*===========================================================================*/
#include<iostream>
#include<string>
using namespace std;
class CBook
{
private:
string name;
string author;
double price;
string publisher;
public:
CBook(){name="无";author="无";price=0.0;publisher="无";}
CBook(const CBook&); // 拷贝构造函数
CBook(string,string,double,string); // 带参数的构造函数
CBook(char*,char*,double,char*); // 带参数的构造函数
~CBook(); //析构函数
void SetName(char*); // 设置书名的成员函数
void SetName(string&); // 设置书名的成员函数
void print()const; // 在屏幕上显示书的信息的成员函数
friend ostream & operator<<(ostream& out,const CBook&); //输出操作符重载函数
};
CBook::CBook(const CBook& t) //拷贝构造函数
{
name=t.name;
author=t.author;
price=t.price;
publisher=t.publisher;
}
CBook::CBook(string a,string b,double c,string d) //带参数的构造函数
{
name=a;
author=b;
price=c;
publisher=d;
}
CBook::CBook(char* a,char* b,double c,char* d) //带参数的构造函数
{
name=a;
author=b;
price=c;
publisher=d;
}
CBook::~CBook() //析构函数
{
cout<<"Destructing"<<name<<endl;
}
void CBook::SetName(char* a) //设置书名的成员函数
{
name=a;
}
void CBook::SetName(string& a) //设置书名的成员函数
{
name=a;
}
void CBook::print()const //在屏幕上显示书的信息的成员函数
{
cout<<"书名:"<<name<<endl
<<"作者:"<<author<<endl
<<"价格:"<<price<<endl
<<"出版社:"<<publisher<<endl;
}
ostream& operator<<(ostream& out,const CBook& t) //输出操作符重载函数
{
out<<"书名:"<<t.name<<endl
<<"作者:"<<t.author<<endl
<<"价格:"<<t.price<<endl
<<"出版社:"<<t.publisher<<endl;
return out;
}
void main()
{
string n="C++程序设计",a="王涛",pub="苏州大学出版社";
CBook b1;
cout<<b1<<endl;
b1.SetName(n);
b1.print();
b1.SetName("VB");
cout<<b1<<endl;
CBook b2=b1;
cout<<b2<<endl;
CBook b3(n,a,35.0,pub);
cout<<b3<<endl;
CBook *b4=new CBook("VC++","李国",45.0,"清华大学出版社");
cout<<*b4<<endl;
delete b4;
}