c++day2

发布于:2024-04-25 ⋅ 阅读:(20) ⋅ 点赞:(0)

 矩形类

#include <iostream>

using namespace std;
class Rec
{
    int length;
    int width;
public:
    void set_length(int l);
    void set_width(int w);
    int get_length();
    int get_width();
    void show();
};
void Rec::set_length(int l){
    length=l;
}
void Rec::set_width(int w){
    width=w;
}
int Rec::get_length(){
    cout<<"请输入长度:";
    cin>>length;
    return length;
}
int Rec::get_width(){
    cout<<"请输入宽度:";
    cin>>width;
    return width;
}
void Rec::show(){
    cout<<"周长:"<<(length+width)*2<<endl;
    cout<<"面积:"<<length*width<<endl;
}

int main()
{
    Rec a;
    a.set_length(a.get_length());
    a.set_width(a.get_width());
    a.show();
    return 0;
}

 

 圆类

#include <iostream>

using namespace std;
class circle
{
    int r;
//    double PI=3.14;
public:
    int set_r(int l);
    void show(int r,double PI=3.14);
};
int circle::set_r(int l){
    r=l;
    return r;
}
void circle::show(int r, double PI){
    cout<<"周长:"<<2*r*PI<<endl;
    cout<<"面积:"<<PI*r*r<<endl;
}
int main()
{
    circle a;
    a.show(a.set_r(3));
    return 0;
}

 Car类

#include <iostream>

using namespace std;
class Car{
private:
    string brand;
    string color;
    int speed;
public:
    void display();
    void accelerate(int amount);
    void set(string brand,string color,int speed);
};
void Car::display(){
    cout<<"brand:"<<brand<<endl;
    cout<<"color:"<<color<<endl;
    cout<<"speed:"<<speed<<endl;
}
void Car::accelerate(int amount){
    speed+=amount;
}
void Car::set(string brand, string color, int speed){
    Car::brand=brand;
    this->color=color;
    this->speed=speed;
}
int main()
{
    Car car;
    car.set("geely","white",10);
    car.display();
    car.accelerate(10);
    car.display();
    return 0;
}