首页 > 试题广场 >

定义一个 Rectangle 类,有长 itsWidth、宽

[问答题]

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

推荐

解:

源程序:

#include <iostream.h>
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)
{
itsWidth = width; 
itsLength = length;
}
int main()
{
Rectangle Rect1;
cout << "Rect1 width: " << Rect1.GetWidth() << endl; 
cout << "Rect1 length: " << Rect1.GetLength() << endl;
int aWidth, aLength;
cout << "Enter a width: "; 
cin >> aWidth;
cout << "\nEnter a length: "; 
cin >> aLength;
Rectangle Rect2(aWidth, aLength);
cout << "\nRect2 width: " << Rect2.GetWidth() << endl; 
cout << "Rect2 length: " << Rect2.GetLength() << endl; 
return 0;
}

程序运行输出:

Rect1 width: 5

Rect1 length: 10

Enter a width: 20

Enter a length: 50

Rect2 width: 20

Rect2 length: 50




发表于 2018-04-18 20:37:07 回复(0)