c++ day 3

发布于:2024-12-18 ⋅ 阅读:(192) ⋅ 点赞:(0)

函数全部类内声明,类外定义

  1. 定义一个矩形类Rec,包含私有属性length、width,包含公有成员方法:
    1. void set_length(int l); //设置长度
    2. void set_width(int w); //设置宽度
    3. int get_length(); //获取长度,将长度的值返回给调用处
    4. int get_width(); //获取宽度,将宽度的值返回给调用处
    5. void show(); //输出周长和面积
      #include <iostream>
      
      using namespace std;
      class Rec
      {
          int length;
          int width;
      public:
          Rec(int length,int width)
          {
              this->length=length;
              this->width=width;
          };
          int get_length();
          int get_width();
          void show();
      };
      
      int Rec::get_length()
      {
          return length;
      }
      int Rec::get_width()
      {
          return width;
      }
      
      void Rec::show()
      {
          cout << "周长=" << 2*(length+width) << endl;
          cout << "面积=" << length*width << endl;
      }
      int main()
      {
          Rec *s1 = new Rec(12,20);
          cout << "length=" << s1->get_length() << endl;
          cout << "width=" << s1->get_width() << endl;
          s1->show();
      
          return 0;
      }
      

  1. 定义一个圆类,包含私有属性半径r,公有成员方法:
    1. void set_r(int r); //获取半径
    2. void show //输出周长和面积,show函数中需要一个提供圆周率的参数PI,该参数有默认值3.14

 

#include <iostream>

using namespace std;
class cir
{
    int &R;
public:
    cir(int &R):R(R)
    {cout << "圆的半径:" << R << endl;}
    void show();
};

void cir::show()
{
    double PI = 3.14;
    cout << "圆的周长为:" << (2*R)*PI << endl;
    cout << "圆的面积为:" << PI*R*R << endl;
}
int main()
{
    int R = 5;
    cir *s1;
    s1 = new cir(R);
    s1->show();
    return 0;
}

 

  1. 定义一个Car类,包含私有属性,颜色color,品牌brand,速度speed,包含公有成员方法:
    1. void display(); //显示汽车的品牌,颜色和速度
    2. void acc(int a); //加速汽车
    3. set函数,设置类中的私有属性
      #include <iostream>
      #include <cstring>
      using namespace std;
      class car
      {
          const string color;
          const string brand;
          int speed;
      public:
          car(const string c,const string b,int s):color(c),brand(b),speed(s){}
          void display();
          void acc(int a);
      };
      
      //显示属性
      void car::display()
      {
          cout << "颜色:" << color << endl;
          cout << "品牌:" << brand << endl;
          cout << "速度:" << speed << endl;
      }
      //加速
      void car::acc(int a)
      {
          cout << "加速后的汽车速度为:" << speed+a << endl;
      }
      int main()
      {
          string x="red";
          string y="hello";
          car s1(x,y,200);
      
          s1.display();
          cout << "加速50" << endl;
          s1.acc(50);
          return 0;
      }
      

ximd


网站公告

今日签到

点亮在社区的每一天
去签到