6-3 类的声明和成员函数的实现–this指针 (20 分)
本题要求声明和实现一个Car类,包括实现其成员函数。
要求如下:
类和函数接口定义:
- 声明一个Car类;
- 三个public成员函数:
(1) disp_welcomemsg(),无返回类型;
(2) get_wheels(),返回一个Car类的数据成员m_nWheels的值;
(3) set_wheels(int),用指定的形参初始化数据成员m_nWheels的值; - 一个私有数据成员m_nWheels,整数类型,代表汽车的车轮数量。
其中,成员函数disp_welcomemsg()显示一条欢迎信息“Welcome to the car world!”。 成员函数get_wheels()返回Car类的私有数据成员m_nWheels。 成员函数set_wheels(int)用指定的形参初始化数据成员m_nWheels。
裁判测试程序样例:
#include
using namespace std;
/* 请在这里填写答案 */
int main()
{
int n;
cin >> n;
Car myfstcar, myseccar; //定义类对象
myfstcar.disp_welcomemsg();//访问成员函数,显示欢迎信息
myfstcar.set_wheels(n); //访问成员函数,设置车轮数量
myseccar.set_wheels(n+4); //访问成员函数,设置车轮数量
//访问成员函数,显示车轮数量
cout << "my first car wheels num = " << myfstcar.get_wheels() << endl;
cout << "my second car wheels num = " << myseccar.get_wheels() << endl;
return 0;
}
输入样例:
4
输出样例:
Welcome to the car world!
my first car wheels num = 4
my second car wheels num = 8
完整代码
#include<iostream>
using namespace std;
class Car{
public:
void disp_welcomemsg();
int get_wheels();
int set_wheels(int n);//其实用void也可以 这里不需要返回值
private:
int m_nwheels;
};
//在类外定义成员函数
void Car::disp_welcomemsg()
{
cout<<"Welcome to the car world!"<<endl;
}
int Car::get_wheels()
{
return m_nwheels;
}
int Car::set_wheels(int n)//将main函数里输入的n传进setwheel函数 再将n赋值给m_nwheels
{
m_nwheels=n;
}
int main()
{
int n;
cin >> n;
Car myfstcar, myseccar; //定义类对象
myfstcar.disp_welcomemsg();//访问成员函数,显示欢迎信息
myfstcar.set_wheels(n); //访问成员函数,设置车轮数量
myseccar.set_wheels(n+4); //访问成员函数,设置车轮数量
//访问成员函数,显示车轮数量
cout << "my first car wheels num = " << myfstcar.get_wheels() << endl;
cout << "my second car wheels num = " << myseccar.get_wheels() << endl;
return 0;
}