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

第一题

按以下要求完成编程:

(1)定义一个抽象类shape,用于代表几何图形,设置计算几何图形体积的外部接口;

(2)由shape类派生出圆柱类cylinder、球sphere;圆柱体类型有私有数据成员半径r,高h;球类有私有数据成员半径r;

(3)结合抽象类的指针或引用,实现就算几何图形体积。

(4)纯虚函数定义:virtual double volume() = 0; 

(5)圆周率取3.1415。const double PI = 3.1415; 

(6)主函数已给出,请直接复制使用 

代码

#include <iostream>

using namespace std;
const double PI = 3.1415;

class shape
{
	public:
		virtual double volume()=0;
};
class cylinder: public shape
{
	private:
		double r,h;
	public:
		cylinder(double radius, double high):r(radius),h(high)
		{
		}
		double volume()
		{
			return PI*r*r*h;
		}
	
};
class sphere:public shape
{
	private:
		double r;
	public:
		sphere(double radius):r(radius)
		{
		}
		double volume()
		{
			return 4*PI*r*r*r/3;
		}
};
int main() {

   shape *p;

   double  r,h;

   cin>>r>>h;

   cylinder cy(r,h);

   sphere sp(r);

   p = &cy;

   cout << p->volume() << endl;    		

   p=&sp;

   cout << p->volume() << endl; 

   return 0;

}

第二题

这道题给出来的主函数和disp是有问题的

update

关于题目问题mooc上发公告了(没错就是我反映的)

设计一个矩阵类,要求矩阵类中重载运算符加(+)和赋值(=),主函数定义类对象并调用重载的运算符。

(1)本题考虑可加(即加与被加矩阵的行列数必须分别相等)和可赋值(等号左值和右值的行列数必须分别相等)情况,如出现不符合条件的运算情况输出“ program terminated! ”,并退出程序结束运行。
(2)要求分别输入矩阵 A 和 B 的行列数,各矩阵元素,然后计算 C =A+B ; A = B ; 并进行输出
(3)定义相应的构造函数和析构函数
(4)类中的成员变量应当有三个:int row,col;分别表示矩阵的行数和列数,另外还需要定义一个一级指针或二级指针m,用来申请动态空间,存放row*col个整数
(5)程序最前面的文件包含请用下面代码:

代码

#include<iostream>
using namespace std;
class Matrix
{
	private:
		int row,col;
		int *p;
	public:
		Matrix(int r,int c):row(r),col(c)
		{
			p = new int[c*r];
			for (int i=0;i<row;i++)
			{
				for (int j=0;j<col;j++)
					cin>>p[i*col+j];
			}
		}
		Matrix()
		{
			p = new int[9];
		}
		void disp()
		{
			for(int i=0;i<row;i++)
			{
				for(int j=0;j<col;j++)
					cout<<p[i*col+j]<<'\t';
				cout<<endl;
			}
		}
		Matrix operator+(Matrix &O)
		{
			if (col!=O.col || row!=O.row)
			{
				cout<<"program terminated!"<<endl;
				exit(0);
			}
			Matrix temp;
			temp.col=col;
			temp.row=row;
			for(int i=0;i<row;i++)
				for(int j=0;j<col;j++)
					temp.p[i*col+j] = p[i*col+j] + O.p[i*col+j];
			return temp;
		}
		Matrix operator=(Matrix D)
		{
			col=D.col;
			row=D.row;
			for (int i = 0; i <row; i++)
			{	
				for (int j = 0; j <col; j++)
					p[i*col+j] = D.p[i*col+j];
			}
			return *this;
		}

};
int main()
{
	int row_a,col_a,row_b,col_b;
	cin>>row_a>>col_a;
	Matrix A(row_a,col_a);
	cin>>row_b>>col_b;
	Matrix B(row_b,col_b),C;	
	C = A + B;
	C.disp();
	cout<<endl;
	A = B;
	A.disp();
	return 0;
}

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sh4ngchen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值