1.编程实现以下功能:
矩形有长a和宽b,现有2个矩形,要求实现矩形相加时可以得到一个新的矩形,
它的长为两个矩形的长a相加,宽为两个矩形的宽b和b相加
要求定义类实现,自己设计,可以输出新矩形的长和宽,矩形相加要求使用运算符+重载实现
#include<iostream>
#include<string>
#include<algorithm>
#include<ctime>
using namespace std;
# if 0
class juxing {
private:
int a;
int b;
public:
juxing(int a=0,int b=0) {
this->a = a;
this->b = b;
}
void show() {
cout << "面积为:" << a * b << endl;
}
juxing operator+(juxing &c) {
juxing d;
d.a=this->a + c.a;
d.b = this->b + c.b;
return d;
}
juxing add(juxing &c) {
juxing d;
d.a = this->a + c.a;
d.b = this->b + c.b;
return d;
}
};
int main() {
juxing j1(3, 4);
juxing j2(4, 5);
juxing d;
d = j1 + j2;
d.show();
juxing d2;
d2=j1.add(j2);
d2.show();
}
#endif
2.编写2个函数模板,分别实现以下操作
输出一维数组元素
对一维数组降序排序
主函数中用double , int 种不同类型的数据进行测试
#include<iostream>
#include<string>
#include<algorithm>
#include<ctime>
using namespace std;
template<class T>
void mysort(T a[],int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j] < a[j + 1]) {
swap(a[j+1], a[j]);
}
}
}
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout <<endl;
}
int main() {
int a[5] = { 11,23,31,24,5 };
double b[5] = { 3.4,7.6,9.1,6.3,2.1 };
mysort(a, 5);
mysort(b, 5);
}
3.定义一个基类图形类,有一个求面的的area函数,该函数为纯虚函数
定义一个派生类圆类,根据需要添加自己的成员,需要有一个area成员函数用来 求面积并输出
定义一个派生类矩形类,根据需要添加自己的成员,需要一个area成员函数用来 求面积并输出
实例化圆类和矩形类两个对象
定义一个基类的指针
将基类指针分别指向派生类的对象,通过指针调用各自的area成员函数,实现多 态
#include<iostream>
#include<string>
#include<algorithm>
#include<ctime>
using namespace std;
class part {
public:
virtual void area() = 0;
/*virtual void area() {
cout << "求图形的面积!" << endl;
}*/
};
class circle:public part {
private:
double r;
public:
circle(double r) {
this->r = r;
}
void area() {
double a;
double pi = 3.14;
a = pi * pow(r, 2);
cout << "圆面积为:"<<a << endl;
}
};
class rectangle:public part {
private:
int width;
int height;
public:
rectangle(int a, int b) {
width = a;
height = b;
}
void area() {
cout <<"矩形面积为:"<< width * height << endl;
}
};
int main(){
part *p;
circle c(4);
rectangle r(3, 4);
p = &c;
p->area();
p = &r;
p->area();
}
4.猜数字游戏:随机给定一个数(要求在1-10之间),然后进行猜数字,如果大了提示大了,小了则提示小了,等于则提示猜测成功
要求使用类实现,自己设计
#include<iostream>
#include<string>
#include<algorithm>
#include<ctime>
using namespace std;
class fun {
int num;
int r;
public:
fun(int a, int b) {
num = a;
r = b;
}
int print() {
if (r > num) {
cout << "大了" << endl;
}
else if (r < num) {
cout << "小了" << endl;
}
else if (r == num) {
cout << "猜测成功!" << endl;
return 1;
}
}
};
int main() {
srand(time(0));
int t, q;
int z;
//1-10的随机数
t = rand() % 10+1;
cout << "猜数字游戏开始啦!" << endl;
for (;;) {
cout << "请输入要猜的数字:";
cin >> q;
fun f(t, q);
z = f.print();
if (z == 1) {
break;
}
}
}