1、矩形类
#include <iostream>
using namespace std;
class Rec //类默认私有属性
{
int length;
int width;
public: //设置共有属性
void set_length(int l);
void set_width(int w);
void show();
int get_length();
int get_width();
};
void Rec::set_length(int l)
{
length = l;
}
void Rec::set_width(int w)
{
width = w;
}
void Rec::show()
{
cout<<"周长="<<(length+width)*2<<endl;
cout<<"面积="<<(length*width)<<endl;
}
int Rec::get_length()
{
return length;
}
int Rec::get_width()
{
return width;
}
int main()
{
Rec a;
a.set_length(3);
a.set_width(2);
int len = a.get_length();
int wid = a.get_width();
cout<<"长="<<len<<endl;
cout<<"宽="<<wid<<endl;
a.show();
return 0;
}
2、圆类
#include <iostream>
using namespace std;
class Cir
{
int r;
public:
void set_r(int a);
void show();
};
void Cir::set_r(int a)
{
r = a;
}
void Cir::show()
{
cout<<"圆的周长为:"<<(2*3.14*r)<<endl;
cout<<"圆的面积为:"<<(3.14*r*r)<<endl;
}
int main()
{
Cir c;
c.set_r(4);
c.show();
return 0;
}
3、Car类
#include <iostream>
using namespace std;
class Car
{
string brand;
string color;
int speed;
public:
void display();
void accelerate(int amount);
void set(string b,string c,int s);
};
void Car::display()
{
cout<<"品牌:"<<brand<<endl;
cout<<"颜色:"<<color<<endl;
cout<<"速度:"<<speed<<endl;
}
void Car::set(string b, string c, int s)
{
brand = b;
color = c;
speed = s;
}
void Car::accelerate(int amount)
{
cout<<"加速前:"<<speed<<endl;
speed += amount;
cout<<"加速后:"<<speed<<endl;
}
int main()
{
Car c;
c.set("五菱宏光","经典银",200);
c.display();
c.accelerate(50);
return 0;
}
思维导图