Fourth practice 1

Fourth practice 1

任务描述

定义一个Rectangle类,有长itsWidth、宽itsLength等属性,重载其构造函数Rectangle()和Rectangle(int width, int length)。

测试输入:1020

预期输出:

Rect1  5
Rect1 length: 10
Enter a  10
Enter a length: 20
Rect2  10
Rect2 length: 20

源代码

#include <iostream>
using namespace std;
class Rectangle
{
public:
	Rectangle();
	Rectangle(int width, int length);
	~Rectangle() {}
	int GetWidth() const { return itsWidth; }
	int GetLength() const { return itsLength; }
private:
	int itsWidth;
	int itsLength;
};
Rectangle::Rectangle()
{
	itsWidth = 5;
	itsLength = 10;
}

Rectangle::Rectangle(int width, int length)
{
	this->itsWidth = width;
	this->itsLength = length;
}

int main()
{
	int width,length;
	cin>>width>>length;

	//输出初始构造函数的值
	Rectangle rc1;
	cout<<"Rect1  "<<rc1.GetWidth()<<endl;
	cout<<"Rect1 length: "<<rc1.GetLength()<<endl;
	//输入长和宽
	cout<<"Enter a  "<<width<<endl;
	cout<<"Enter a length: "<<length<<endl;
	//输出重载后的构造函数的值
	Rectangle rc2(width,length);
	cout<<"Rect2  "<<rc2.GetWidth()<<endl;
	cout<<"Rect2 length: "<<rc2.GetLength()<<endl;
	return 0;
}

原文地址:https://www.cnblogs.com/lightice/p/12911025.html