头歌C++ 面向对象 - 类和对象的创建和使用

第1关:设计一个学生信息类:

#include <iostream>
using namespace std;

class StInfo
{
    /********* Begin *********/
  public:  //在此处声明StInfo类
    int SID;
    char *Name;
    char *Class;
    char *Phone;
   void SetInfo(int sid,char *name,char *cla,char *phone);
           void PrintInfo();
    
    /********* End *********/
};

/********* Begin *********/
//在此处定义StInfo类
void StInfo::SetInfo(int sid,char *name,char* cla,char* phone){
     SID=sid;
     Name=name;
     Class=cla;
     Phone=phone; 
}
void StInfo::PrintInfo()
{
    cout<<"学号:"<<SID<<endl;
    cout<<"姓名:"<<Name<<endl;
    cout<<"班级:"<<Class<<endl;
    cout<<"手机号:"<<Phone<<endl;
}

/********* End *********/

第2关:设计一个长方形类    后段没有main函数,因为头歌平台自带了main函数,再加会报重复,若有需要可以自行添加。

#include<iostream>
using namespace std;
/********* Begin *********/
class Rectangle
{
    //在此处实现Rectangle类
    
private:
     int height;
     int width;
public:
    void Set(int h,int w);
    int GetArea(); 
    
};
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 rect;
    rect.Set(h,w);
    return rect;
    
    
    /********* End *********/
}

int GetRectArea(Rectangle rect)
{
    /********* Begin *********/
    //返回 rect 对象的面积
    
     return rect.GetArea();

    
    /********* End *********/
}

第3关:设计汽车类

#include <iostream>
using namespace std;

/********* Begin *********/
//在此处实现一个汽车类
class Car
{  public:
        string door;
        string light;
        int  speed; 
   void  opdoor()
   {door="ON";}
   void  cldoor()
    {door="OFF";}
   void   oplight()
   {light="ON";}
   void   cllight()
   {light="OFF";}
   void   spspeed()
    {speed+=10;}
   void   nospeed()
   {speed-=10;}
   void printfcar()
   {cout<<"车门 "<< door<<endl;
   cout<<"车灯 "<< light<<endl;
   cout<<"速度 "<< speed<<endl;}
 };
/********* End *********/

int main()
{
    /********* Begin *********/
    //在此处解析执行输出汽车的整体状态
	char cmds[25];
    cin>>cmds;
    Car car;
    car.door="OFF";
    car.light="OFF";
    car.speed=0;
    for(int i=0;i<25;i++)
	{
			if(cmds[i]=='1')
			car.opdoor();
			if(cmds[i]=='2')
			car.cldoor();
			if(cmds[i]=='3')
			car.oplight();
			if(cmds[i]=='4')
			car.cllight();
			if(cmds[i]=='5')
			car.spspeed();
			if(cmds[i]=='6')
			car.nospeed();
	}
	car.printfcar(); 

  • 28
    点赞
  • 110
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值