请定义类Room来计算并输出面积
在main函数中定义图像r1,通过调用带参构造函数进行初始化,定义对象r2,调用input进行长度和宽度的初始化
#include <iostream>
using namespace std;
class Room{
// https://www.runoob.com/cplusplus/cpp-classes-objects.html
public:
// 类的成员
float length; // 长度
float width; // 宽度
// 函数声明
Room(); // 无参的构造函数
Room(float l,float w); // 有参的构造函数
void input();
float area();
};
// 成员函数的定义
Room::Room(){
}
Room::Room(float l,float w){
length=l;
width=w;
}
void Room::input(){
cout<<"请输入长度:";
cin>>length;
cout<<"请输入宽度:";
cin>>width;
}
float Room::area(){
return length*width;
}
int main(void){
// https://www.cnblogs.com/mr-wid/archive/2013/02/18/2916309.html
Room r1(3,4); // 调用有参的构造函数创建一个对象r1
cout<<r1.area()<<endl; // 调用area函数,打印面积
Room r2; // 调用无参的构造函数创建对象r2
r2.input(); // 调用input方法给 成员赋值
cout<<r2.area()<<endl; // 调用area函数 打印面积
return 0;
}