定义矩形类Rectangle
#include <iostream>
using namespace std;
class Rectangle {
public:
Rectangle(int length, int width) : Length(length), Width(width) {
cout << "Rectangle's constructor is called!" << endl;
}
~Rectangle() {
cout << "Rectangle's destructor is called!" << endl;
}
int GetArea() const {
return Length * Width;
}
int GetLength() const {
return Length;
}
int GetWidth() const {
return Width;
}
private:
int Length;
int Width;
};
int main() {
int length, width;
cin >> length >> width;
Rectangle rect(length, width);
cout << "Length = " << rect.GetLength() << endl;
cout << "width = " << rect.GetWidth() << endl;
cout << "Area = " << rect.GetArea() << endl;
return 0;
}
Rectangle(int length, int width) : Length(length), Width(width)
是Rectangle
类的构造函数,它接受两个整型参数length
和width
,用于初始化类中的私有成员变量Length
和Width
。构造函数使用初始化列表的方式进行成员变量的初始化,这种方式比在构造函数体内赋值更高效,尤其是对于成员变量是对象类型且有构造函数的情况。在构造函数被调用时,会输出提示信息"Rectangle's constructor is called!"
,用于在控制台显示构造函数执行的情况,方便调试和了解对象创建的时机。- 成员函数
GetLength
和GetWidth
:int GetLength() const 和 int GetWidth() const 这两个函数分别用于获取矩形的长度和宽度。它们只是简单地返回对应的私有成员变量Length和Width的值,并且也被声明为const,表示不会修改对象的状态。