C++ OJ习题练习(七)设计矩形类rectangle

Problem Description

定义并实现一个矩形类rectangle,有长(length)、宽(wide)两个属性,成员函数area计算矩形的面积,成员函数setxx和getxx设置和获取length或者wide的值,成员函数display输出矩形的信息(长,宽,面积),要求定义构造函数、拷贝构造函数、赋值运算符函数,能使用对象数组。

//你的代码将被嵌在这里
int main()
{
    rectangle r1(3,4);     //定义一个矩形r1,长为3,宽为4
    r1.display();     //输出矩形r1的有关信息
    rectangle r2;     //定义一个矩形r2
    r2=r1;
    r2.display();     //输出矩形r2的有关信息
    r2.setlength(10);     //把矩形r2的长length改为10
    r2.setwide(20);     //把矩形r2的宽wide改为20
    r2.display();     //再输出矩形r2的有关信息
    rectangle r3(r1);
    r3.display();     //输出矩形r3的有关信息
    rectangle r4[2];     //定义矩形数组r4
    for(int i=0;i<2;i++)     //输出矩形数组r4中各个矩形的信息
           r4[i].display();
    return 0;
}

Sample Output

message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=10 wide=20 area=200
message of the rectangle:length=3 wide=4 area=12
message of the rectangle:length=0 wide=0 area=0
message of the rectangle:length=0 wide=0 area=0

解题代码

#include 
using namespace std;
class rectangle{
    int length,wide;
public:
    rectangle():length(0),wide(0){}
    rectangle(int len,int wid){length = len;wide = wid;}
    rectangle(const rectangle &p)
    {
        if(this == &p)return;
        length = p.length;
        wide = p.wide;
    }
    rectangle & operator=(const rectangle &p)
    {
        if(this == &p) return *this;
        length = p.length;
        wide = p.wide;
        return *this;
    }
    void setlength(int len){length = len;}
    int getlength(){return length;}
    void setwide(int wid){wide = wid;}
    int getwide(){return wide;}
    int area(){return length * wide;}
    void display() {cout << "message of the rectangle:length=" << length << " wide="<< wide << " area=" << area()<<endl;}
};

你可能感兴趣的:(C/C++,c++,oj系统)