类与对象(二)

使用类计算矩形的面积。定义并实现一个矩形类,有长和宽两个属性,由成员函数计算矩形的面积。矩形类Rectang接口定义如下:

class Rectangle {

public:

    void setLength(int l);//设置矩形的长度

    void setWidth(int w); //设置矩形的宽度

    int getArea();    //计算并返回矩形的面积

private:

    int length, width;  //矩形的长度和宽度        

};

请实现Rectangle类的成员函数。
 

测试程序样例:

#include <iostream>
using namespace std;
 
class Rectangle {
public:
    void setLength(int l);//设置矩形的长度
    void setWidth(int w); //设置矩形的宽度
    int getArea();        //计算并返回矩形的面积
private:
    int length, width;    //矩形的长度和宽度 
};
 
int main()
{
    Rectangle r;
    int len, w;
    cin >> len >> w;
    r.setLength(len);
    r.setWidth(w);
    cout << r.getArea() << "\n";
    return 0;
}
/* 你的代码将嵌在这里 */

 

代码如下:

void Rectangle::setLength(int l)

{

       length=l;

}

void Rectangle::setWidth(int w)

{

       width=w;

}

int Rectangle::getArea()

{

       return length*width;

}

 

posted @ 2018-12-14 22:55  .Daylight  阅读(371)  评论(0编辑  收藏  举报