题目展示
实验题目1
设计一个Car类,它的数据成为要能描述一辆车的品牌、型号、出厂年份和价格,成员函数包括提供合适的途径来访问数据成员,在main函数中定义类的对象,并调用想要的成员函数。
要求:
① 能够自己输入车辆信息,有相应的提示语句,如:‘please input xxx’;
② 可以展示车辆信息;
③ 需采用对象数组
实验题目2
定义一个Point类,用来产生平面上的点对象。两点决定一条线段,即线段由点构成。因此,Line类使用Point类的对象作为数据成员,然后在Line类的构造函数中求出线段的长度。
要求:
①定义两个类Point和Line;
②能够自己输入点的坐标(x,y),有相应的提示语句,如:‘please input xxx’;
③可以输出线段的长度
④必须基于面向对象的方式实现,不可直接用面向过程的方式实现
题目解答
题目一
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
class Car
{
private:
string brond;
string type;
string date;
string price;
public:
string Getpinpai();
string Getxinghao();
string Getchuchang();
string Getjiage();
Car(string p, string x, string c, string j);
};
string Car::Getpinpai()
{
return brond;
}
string Car::Getxinghao()
{
return type;
}
string Car::Getchuchang()
{
return date;
}
string Car::Getjiage()
{
return price;
}
Car::Car(string p, string x, string c, string j)
{
brond = p;
type = x;
date = c;
price = j;
}
int main()
{
int m, n, a = 1;
string p, x, c, j;
vector<vector<string> >A(4);
cout << "需录取信息的车辆总数为:" << endl;
cin >> m;
for (a = 0; a < m; a++)
{
cout << "请提供第" << a + 1 << "辆车的品牌:" << endl;
cin >> p;
cout << "请提供第" << a + 1 << "辆车的型号:" << endl;
cin >> x;
cout << "请提供第" << a + 1 << "辆车的出厂日期:" << endl;
cin >> c;
cout << "请提供第" << a + 1 << "辆车的价格:" << endl;
cin >> j;
cout << "__________________\n" << endl;
A[a] = { p,x,c,j };
}
for (a = 0; a < m; a++)
{
cout << "________________" << "\n" << "第" << a + 1 << "辆车的品牌为:" << A[a][0] << "\n" << "第" << a + 1 << "辆车的型号为:" << A[a][1] << "\n" << "第" << a + 1 << "辆车的出厂日期为:" << A[a][2] << "\n" << "第" << a + 1 << "辆车的价格为:" << A[a][3] << endl;
}
return 0;
};
题目二
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
class Point {
private:
double x;
double y;
public:
Point() {}
Point(double x, double y) {
this->x = x;
this->y = y;
}
void Setx(double x) {
this->x = x;
}
int Getx() {
return x;
}
void Sety(double y) {
this->y = y;
}
int Gety() {
return y;
}
};
class Line {
private:
double x1;
double x2;
double y1;
double y2;
public:
Line() {}
Line(int x1, int y1, int x2, int y2) {
this->x1 = x1;
this->x2 = x2;
this->y1 = y1;
this->y2 = y2;
}
void Set(int x1, int y1, int x2, int y2) {
this->x1 = x1;
this->x2 = x2;
this->y1 = y1;
this->y2 = y2;
}
double length() {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
};
int main() {
Point p1;
Point p2;
Line l;
cout << "Please input the first point:\n";
int x, y;
cin >> x >> y;
p1.Setx(x); p1.Sety(y);
cout << "Please input the other point:\n";
cin >> x >> y;
p2.Setx(x); p2.Sety(y);
l.Set(p1.Getx(), p1.Gety(), p2.Getx(), p2.Gety());
cout << "the line's length is:\n";
cout << l.length();
}