内容提要
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;
}