【Educoder作业】C++ 面向对象 - 类和对象的创建和使用
这个大坑嗷…本来以为没时间开了,结果网课了时间多起来了,补上吧
由于本身掌握不是很精通,说的不对即使指正/抱拳
T1 设计一个学生信息类
类的成员和成员函数可以分为 p r i v a t e , p u b l i c , p r o t e c t e d private,public,protected private,public,protected。做题都放 p u b l i c public public就没啥问题吧。
#include <iostream>
using namespace std;
class StInfo
{
/********* Begin *********/
//在此处声明StInfo类
public :
void SetInfo(int s, char *n, char *c, char *p) {
SID = s, Name = n, Class = c, Phone = p;}
void PrintInfo() {
cout << "学号:" << SID <<endl ;
cout << "姓名:" << Name << endl ;
cout << "班级:" << Class <<endl ;
cout << "手机号:" << Phone << endl ;
}
private :
int SID;
char *Name, *Class, *Phone;
/********* End *********/
};
/********* Begin *********/
//在此处定义StInfo类
// int main() {
// int s;
// char n[110], c[110], p[110];
// cin >> s;
// cin >> n >> c >> p ;
// StInfo a = StInfo(s, n, c, p);
// a.PrintInfo();
// }
/********* End *********/
T2 设计一个长方形类
我们发现,这个跟结构体其实是很像的。在大多数方面和 s t r u c t struct struct基本没有区别。
/********* Begin *********/
class Rectangle
{
//在此处实现Rectangle类
public :
void Set(int h, int w);
int GetArea();
private :
int height, width;
};
void Rectangle :: Set(int h, int w) {
height = h;
width = w;
}
int Rectangle :: GetArea() {
return height * width;
}
/********* End *********/
Rectangle GetRect(int h,int w)
{
/********* Begin *********/
//返回一个 h*w 的 Rectangle 对象
Rectangle re;
re.Set(h, w);
return re;
/********* End *********/
}
int GetRectArea(Rectangle rect)
{
/********* Begin *********/
//返回 rect 对象的面积
return rect.GetArea();
/********* End *********/
}
/********* Begin *********/
class Rectangle
{
//在此处实现Rectangle类
public:
void Set(int h, int w);
int GetArea();
private:
int height;
int width;
};
/********* End *********/
Rectangle GetRect(int h,int w)
{
/********* Begin *********/
//返回一个 h*w 的 Rectangle 对象
Rectangle a;
a.Set(h, w);
return a;
/********* End *********/
}
int GetRectArea(Rectangle rect)
{
/********* Begin *********/
//返回 rect 对象的面积
int area = rect.GetArea();
return area;
/********* End *********/
}
T3 设计汽车类
#include <iostream>
using namespace std;
/********* Begin *********/
//在此处实现一个汽车类
class Car
{
public :
Car() {
Door = Light = Speed = 0;}
void OpenDoor() {
Door = true;}
void CloseDoor() {
Door = false;}
void OpenLight() {
Light = true;}
void CloseLight() {
Light = false;}
void UpSpeed() {
Speed += 10;}
void DownSpeed() {
/*if (Speed) */Speed -= 10;}
void Print() {
cout << "车门 " << (Door ? "ON" : "OFF") << endl ;
cout << "车灯 " << (Light ? "ON" : "OFF") << endl ;
cout << "速度 " << Speed << endl ;
}
private :
bool Door, Light;
int Speed;
};
/********* End *********/
int main()
{
/********* Begin *********/
//在此处解析执行输出汽车的整体状态
Car car;
char cmds[25];
cin>>cmds;
char *p = cmds;
while (*p != '\0') {
int opt = (*p) - '0';
if (opt == 1) car.OpenDoor();
if (opt == 2) car.CloseDoor();
if (opt == 3) car.OpenLight();
if (opt == 4) car.CloseLight();
if (opt == 5) car.UpSpeed();
if (opt == 6) car.DownSpeed();
p ++ ;
}
car.Print();
/********* End *********/
}