12月测试题:4.书籍类设计与测试

要求在Date类基础上采用类组合的思想,
设计一个书籍类并测试之,该类包括出版日期(即一个日期类的对象)、书名等。涉及带参构造函数,能提供显示书籍信息的函数。

前置代码:

#include <iostream>
#include <string>
using namespace std;
class Date
{
private:
	int year,month,day;
public:
	Date(int y=0,int m=0,int d=0)
	{
		year=y;
		month=m;
		day=d;
	}
	void Show()
	{
		cout<<year<<"-"<<month<<"-"<<day<<endl;
	}
};
class Book
{
private:	
	Date dx;	
	string name;

后置代码:

int main()
{
   int a,b,c;
   cin>>a>>b>>c;
   Date dd(a,b,c);
   Book x(2018,9,1,"C++"),y(dd,"C");
   x.Show();
   y.Show();
   return 0;
}

难度较低,考点为类的组合
题解如下:

#include <iostream>
#include <string>
using namespace std;
class Date
{
private:
	int year,month,day;
public:
	Date(int y=0,int m=0,int d=0)
	{
		year=y;
		month=m;
		day=d;
	}
	void Show()
	{
		cout<<year<<"-"<<month<<"-"<<day<<endl;
	}
};
class Book
{
	private:	
		Date dx;	
		string name;
	public:
		Book(int a,int b,int c,const string &d):dx(a,b,c)
		{	//输入3个int一个string的book构造函数
		//这里用到的是组合的格式 
			name=d;
		}
		Book(Date &dd,const string &d)
		{//这是一个Date,一个string参数的book构造函数
		//同样是组合的形式 
			dx=dd;
			name=d;
		}
		void Show()
		{//调用Date中的show函数 
			dx.Show();
			cout<<name<<endl;
		}
};
	
int main()
{
   int a,b,c;
   cin>>a>>b>>c;
   Date dd(a,b,c);
   Book x(2018,9,1,"C++"),y(dd,"C");
   x.Show();
   y.Show();
   return 0;
}

发布了28 篇原创文章 · 获赞 12 · 访问量 3811

猜你喜欢

转载自blog.csdn.net/q767410241/article/details/84844754