定义一个矩形类Rec,包含私有属性length,width,有以下成员函数:
void set length(int l);//设置长度
void set width(int w); //设置宽度
int get length(); //获取长度
int get_width(); //获取宽度
void show(); //输出周长和面积
#include <iostream>using namespace std;
class Rec
{
public:void set_length(int l);void set_width(int w);int get_length();int get_width();void show();
private:int length;int width;
};
void Rec::set_length(int l)
{length=l;
}
void Rec::set_width(int w)
{width=w;
}
int Rec::get_length()
{cout << "length=" << length << endl;return length;
}
int Rec::get_width()
{cout << "width=" << width << endl;return width;
}
void Rec::show()
{int c=(length+width)*2;int s=length*width;cout << "矩形周长为:" << c << endl;cout << "矩形面积为:" << s << endl;
}
int main()
{int l,w;cin >> l >> w;Rec r1;r1.set_length(l);r1.set_width(w);r1.get_length();r1.get_width();r1.show();return 0;
}
定义一个圆类,包含私有属性半径r,设置公有函数,setr为私有属性r赋值,show函数,输出周长和面积,show函数中,PI参数有默认值为3.14
#include <iostream>
using namespace std;
class stu
{
private:double r;
public:void show(double PI=3.14);void set_r(double n);
};
void stu::set_r(double n)
{r=n;
}
void stu::show(double PI)
{double c=2*r*PI;double s=PI*PI*r;cout << "周长为:" << c << endl;cout << "面积为:" << s << endl;
}
int main()
{double n;cin >> n;stu s1;s1.set_r(n);s1.show();return 0;
}
创建一个Car类,包含以下成员:品牌(brand):字符串类型,颜色(color):字符串类型,速度(speed):整数类型;实现以下成员函数:void display():用于显示汽车的品牌、颜色和速度。voidaccelerate(int amount):用于加速汽车,速度增加指定的量,void set(string b,string c,int s):用于给私有属性赋值。
#include <iostream>using namespace std;
class car
{
private:string brand;string color;int speed;
public:void set(string b,string c,int s);void accelerate(int amount);void display();
};
void car::set(string b, string c, int s)
{brand=b;color=c;speed=s;
}
void car::accelerate(int amount)
{speed+=amount;cout << "加速后的速度为:" << speed << endl;
}
void car::display()
{cout << "品牌:" << brand << endl;cout << "颜色:" << color << endl;cout << "速度:" << speed << endl;
}
int main()
{car c1;string b="大众";string c="blue";int s=269;int a=10;c1.set(b,c,s);c1.display();c1.accelerate(a);return 0;
}
思维导图