定义一个Rectangle类,有长itsWidth、宽itsLength等属性,重载其构造函数Rectangle()和Rectangle(int width, int length)。
测试输入:10
,20
预期输出:
Rect1 width: 5
Rect1 length: 10
Enter a width: 10
Enter a length: 20
Rect2 width: 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 width: "<<rc1.GetWidth()<<endl;
cout<<"Rect1 length: "<<rc1.GetLength()<<endl;
//输入长和宽
cout<<"Enter a width: "<<width<<endl;
cout<<"Enter a length: "<<length<<endl;
//输出重载后的构造函数的值
Rectangle rc2(width,length);
cout<<"Rect2 width: "<<rc2.GetWidth()<<endl;
cout<<"Rect2 length: "<<rc2.GetLength()<<endl;
return 0;
}
原文:https://www.cnblogs.com/lightice/p/12911025.html