c13_10.cpp

来自「这是编程之道C-C++中的源代码,很简练,可以用于相关教学和重新熟悉C-C++时」· C++ 代码 · 共 56 行

CPP
56
字号
#include <iostream >
using namespace std;

class CRectangle				//定义矩形类Rectangle
{
public:
	CRectangle();
	void SetLength(int length);
	int GetLength() const;		// const 指示该函数内限制对成员变量的修改。
	void SetWidth(int width); 
	int GetWidth() const ;
private:
	int itsLength;
	int itsWidth;
};

CRectangle::CRectangle()
{
	itsWidth = 5;
	itsLength = 10;
}

void CRectangle::SetLength(int length)
{
	this->itsLength = length;	//显式地使用this指针来引用成员变量
}

int CRectangle::GetLength() const 
{
	return this->itsLength;			//显式地使用this指针来引用成员变量
}

void CRectangle::SetWidth(int width) 
{
	itsWidth = width;				//this指针被隐式地使用
} 

int CRectangle::GetWidth() const 
{
	return itsWidth;				//this指针被隐式地使用
}
//-------------------------------------------------------//
int main()
{
	CRectangle	theRect;
	cout << "矩形theRect的长是 " << theRect.GetLength() << endl;
	cout << "矩形theRect的宽是 " << theRect.GetWidth() << endl;
	//调用成员函数,重新设定矩形theRect的长和宽
	theRect.SetLength(20); 
	theRect.SetWidth(10);
	cout << "矩形theRect的长是 " << theRect.GetLength() << endl;
	cout << "矩形theRect的宽是 " << theRect.GetWidth() << endl;

	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?