qfedu-cpp-level/day4/homework/h5.cpp

80 lines
1.5 KiB
C++
Raw Normal View History

2023-07-27 21:04:06 +08:00
// 继上面的Car类 设计Person类并设置Car类为Person类的友元类使得在Person类的成员函数直接访问 Car对象的所有成员。
// 【提示】Person类的构造函数传入 Car类的对象 增加Person的成员函数用于操作Car类的成员函数或访问Car对象的属性。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Car
{
friend class Person;
public:
Car(const string &color, int weight) : color(color), weight(weight) {}
public:
void driver()
{
cout << "驾车 " << this->weight << " 车重" << endl;
}
void start()
{
cout << "启动 " << this->color << " 颜色的车" << endl;
}
void stop()
{
cout << "停车" << endl;
}
private:
string color; // 颜色
int weight; // 重量
};
class Person
{
// friend class Car;
public:
Person(Car &car) : tcar(car) {}
public:
void setCarColor(const string &color)
{
// strcpy(tcar.color, color);
tcar.color = color;
}
void setCarWeight(int weight)
{
tcar.weight = weight;
}
void show()
{
cout << "驾驶着一辆" << tcar.color << ", 重" << tcar.weight << "千克的车辆" << endl;
}
private:
Car &tcar;
};
void test()
{
Car car("红色", 1000);
Person person(car);
person.setCarColor("蓝色");
person.setCarWeight(1230);
car.start();
car.driver();
car.stop();
person.show();
}
int main()
{
test();
return 0;
}