实验题目1 设计一个Car类,它的数据成为要能描述一辆车的品牌、型号、出厂年份和价格,成员函数包括提供合适的途径来访问数据成员,在main函数中定义类的对象,并调用想要的成员函数。
要求:
① 能够自己输入车辆信息,有相应的提示语句,如:‘please input xxx’;
② 可以展示车辆信息;
③ 需采用对象数组
实验题目2 定义一个Point类,用来产生平面上的点对象。两点决定一条线段,即线段由点构成。因此,Line类使用Point类的对象作为数据成员,然后在Line类的构造函数中求出线段的长度。
要求:
- 定义两个类Point和Line;
- 能够自己输入点的坐标(x,y),有相应的提示语句,如:‘please input xxx’;
- 可以输出线段的长度
- 必须基于面向对象的方式实现,不可直接用面向过程的方式实现
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Car{
public:
Car(){cout<<"Constructor without parameters."<<endl;}
Car(string b,string m,string c,string l,string d,float p);
Car(const Car&);
~Car(){cout<<"Deconstructor is called."<<endl;}
void SetBrand(string brand){sBand=brand;}
void SetModel(string model){sModel=model;}
void SetColor(string color){sColor=color;}
void SetLocation(string location){sLocation=location;}
void SetDate(string date){sDate=date;}
void SetPrice(float f){fPrice=f;}
string GetBrand(){return sBand;}
string GetModel(){return sModel;}
string GetColor(){return sColor;}
string GetLocation(){return sLocation;}
string GetDate(){return sDate;}
float GetPrice(){return fPrice;}
void printInfo();
void Compare(const Car&);
private:
string sBand;
string sModel;
string sColor;
string sLocation;
string sDate;
float fPrice;
};
Car::Car(string b,string m,string c,string l,string d,float p)
{
sBand=b;
sModel=m;
sColor=c;
sLocation=l;
sDate=d;
fPrice=p;
cout<<"Constructor with parameters."<<endl;
}
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x;
double y;
public:
Point() {}
Point(double _x, double _y) : x(_x), y(_y) {}
double getX() const { return x; }
double getY() const { return y; }
};
class Line {
private:
Point start;
Point end;
double length;
public:
Line(Point _start, Point _end) : start(_start), end(_end) {
double deltaX = end.getX() - start.getX();
double deltaY = end.getY() - start.getY();
length = sqrt(deltaX * deltaX + deltaY * deltaY);
}
double getLength() const { return length; }
};
int main() {
double x1, y1, x2, y2;
cout << "Please input the start point's coordinate (x, y): ";
cin >> x1 >> y1;
cout << "Please input the end point's coordinate (x, y): ";
cin >> x2 >> y2;
Point start(x1, y1);
Point end(x2, y2);
Line line(start, end);
cout << "The length of the line is: " << line.getLength() << endl;
return 0;
}