定义矩形类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类的构造函数,它接受两个整型参数lengthwidth,用于初始化类中的私有成员变量LengthWidth。构造函数使用初始化列表的方式进行成员变量的初始化,这种方式比在构造函数体内赋值更高效,尤其是对于成员变量是对象类型且有构造函数的情况。在构造函数被调用时,会输出提示信息"Rectangle's constructor is called!",用于在控制台显示构造函数执行的情况,方便调试和了解对象创建的时机。
    • 成员函数GetLengthGetWidth:int GetLength() const 和 int GetWidth() const 这两个函数分别用于获取矩形的长度和宽度。它们只是简单地返回对应的私有成员变量Length和Width的值,并且也被声明为const,表示不会修改对象的状态。

全部评论

相关推荐

03-29 14:19
门头沟学院 Java
你背过凌晨4点的八股文么:加油同学,人生的容错率很高,只是一个暑期罢了,后面还有很多机会!
点赞 评论 收藏
分享
运营3年修炼中接简历辅导:你的科研项目经历里,只写了你的动作,没有写你的思考和成果,不要只写使用什么进行了什么,这等于罗列你的任务,简历是为了突出你的优秀,你在什么样的任务背景下,克服了什么样的困难,针对性地做了哪些事情,最后达成了什么成果(用数据体现你的成果和效率)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务