C++ 实验四 : 运算符重载和虚函数

内容提要

1.对于类MyString,要求重载‘+’运算符后可以计算表达式:a=b+c;表示两个字符串连接。其中a,b,c都是类MyString的对象。

2.使用虚函数编写程序求球体和圆柱体的体积及表面积。由于球体和圆柱体都可以看作由圆继承而来,所以可以定义圆类Circle作为基类。在Circle类中定义一个数据成员radius和两个虚函数area()和volume()。由Circle类派生Sphere类和Column类。在派生类中对虚函数area()和volume()重新定义,分别求球体和圆柱体的体积及表面积。

基本要求
重载相应的运算符并编写程序,能运用虚函数编写程序测试并提交程序。

1. 重载+

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>

using namespace std;


class Mystring {
public:
	Mystring(const char* ptr = "")
		:_ptr(new char[strlen(ptr) + 1])
	{
		strcpy(_ptr, ptr);
	}


	Mystring operator+(Mystring& s) {
		int len1 = strlen(_ptr);
		int len2 = strlen(s._ptr);

		char* tmp = new char[len1 + len2 + 1];

		strcpy(tmp, _ptr);
		strcpy(tmp + len1, s._ptr);
		
		Mystring ret(tmp);

		delete[] tmp;
		return ret;
	}

	friend ostream& operator<<(ostream& _cout, Mystring& s);

private:
	char* _ptr;
};

ostream& operator<<(ostream& _cout, Mystring& s) {
	_cout << s._ptr;
	return _cout;
}



int main() {
	Mystring a("1324");
	Mystring b("abcd");
	Mystring c;

	c = a + b;

	cout << c << endl;

	return 0;
}

2. 虚函数求体积表面积

#include <iostream>

using namespace std;

double PI = acos(-1);


//圆,接口类
class Circle {
public:
	//表面积
	virtual double area() = 0;
	//体积
	virtual double volume() = 0;

protected:
	//半径
	double _r;
};

//球
class Sphere :public Circle {
public:
	Sphere(double r = 0.0) {
		_r = r;
	}

	//表面积
	virtual double area() {
		return 4 * PI * _r * _r;
	}

	//体积
	virtual double volume() {
		return 4.0/3 * PI * _r * _r * _r;
	}
};

//圆柱
class Column :public Circle {
public:
	Column(double r = 0, double h = 0) {
		_r = r;
		_h = h;
	}

	//表面积
	virtual double area() {
		return 2 * (PI * _r * _r) + (PI * 2 * _r * _h);
	}

	//体积
	virtual double volume() {
		return PI * _r * _r * _h;
	}

private:
	//高
	double _h;
};


int main() {
	double rS, rC, h;

	cout << "请输入球体的半径:";
	cin >> rS;

	cout << "请输入圆柱体的半径:";
	cin >> rC;

	cout << "请输入圆柱体的高:";
	cin >> h;

	cout << endl;

	Sphere sphere(rS);
	Column column(rC, h);

	cout << "球体的半径为:" << rS << endl;
	cout << "球体的表面积为:" << sphere.area() << endl;
	cout << "球体的体积为:" << sphere.volume() << endl << endl;
	
	cout << "圆柱体的半径为:" << rC << endl;
	cout << "圆柱体的表面积为:" << column.area() << endl;
	cout << "圆柱体的体积为:" << column.volume() << endl << endl;

	return 0;
}
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

殇&璃

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

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

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

打赏作者

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

抵扣说明:

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

余额充值