面向对象程序设计及C++mooc编程(第五章)--by sCh3n

第一题

首先定义一个类POINT,有两个int型的保护数据成员x、y表示该类对象在二维坐标系中的坐标位置,定义如下三个公有成员函数:

(1)  构造函数:设置点的初始值;

(2)   成员函数change改变坐标位置

(3)   成员函数show显示点的位置,具体输出形式请参考下面的输出提示;cout<<"("<<x<<","<<y<<")"<<endl;

然后,以类POINT为基类定义派生类CIRCLE,其中增加一个私有数据成员int r表示该圆的半径,定义如下两个公有成员函数:

(1)  构造函数:负责调用基类的构造函数及为本类的半径成员初始化

(2)重新定义show函数显示圆心的位置及半径的值,

#include<iostream>
using namespace std;

class POINT
{
	protected:
		int x,y;
	public:
		POINT(int a,int b):x(a),y(b)
		{
		}
		void change(int a,int b)
		{
			x=a;y=b;
		}
		void show()
		{
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
};
class CIRCLE:public POINT
{
	private:
		int r;
	public:
		CIRCLE(int a,int b,int c):POINT(a,b),r(c)
		{
		}
		void show()
		{
			cout<<"the center of the circle is:\n";
			POINT::show( );
            cout<<"the radius is:"<<r<<endl;
		}
};
int main ( )

{

    POINT p (2, 3);

    CIRCLE c (3, 4, 5);

    cout<<"original p:\n";

    p.show ();

    p.change (20,30);

    cout<<"changed p:\n";

    p.show ();

    cout<<"original c:\n";

    c.show ( );

    c.change (30,40);

    cout<<"changed c:\n";

    c.show ( );

    return 0;

}

第二题

图5-13(见教材p138)是一个多重继承的类继承关系示意图,各类的主要数据成员有说明,请自己定义合理的成员函数,编程实现该继承关系的程序,并定义一个在职研究生对象,先输入相关信息,再输出。

关于数据成员:

数据类Data:成员string name,保存姓名;

教师类Teacher:增加成员float sal,保存工资;

学生类Student:增加成员string id,保存学号;

研究生类Postgrad:增加成员 string dn,保存系别;

教师中的在职研究生类Tpost:不另外定义成员。

关于成员函数: 

    各类定义输出所有数据

成员的函数void print()。

#include<iostream>
using namespace std;
class Data
{
	protected:
		string name;
	public:
		Data(string a):name(a)
		{
		}
};
class Teacher:public virtual Data
{
	protected:
		float sal;
	public:
		Teacher(string a,float b):Data(a),sal(b)
		{
		}
};
class Student:public virtual Data
{
	protected:
		string id;
	public:
		Student(string a,string b):Data(a),id(b)
		{
		}
};
class Postgrad:public Student
{
	protected:
		string dn;
	public:
		Postgrad(string a,string b,string c):Data(a),Student(a,b),dn(c)
		{
		}
};
class Tpost:public Teacher,public Postgrad
{
	public:
		Tpost(string n,float s,string i,string d):Data(n),Teacher(n,s),Postgrad(n,i,d)
		{
		}
};
int main()
{
	string name,id,dn;
	float sal;
	cin>>name>>id>>dn>>sal;
	Tpost tp(name,sal,id,dn);
	cout<<"The teacher and postgraduate:"<<endl;
	cout<<"name="<<name<<endl;
	cout<<"id="<<id<<endl;
	cout<<"dn="<<dn<<endl;
	cout<<"sal="<<sal<<endl;
}
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sh4ngchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值