码迷,mamicode.com
首页 > 其他好文 > 详细

类与对象(二)

时间:2018-12-15 00:11:41      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:space   inf   ret   宽度   bubuko   tle   返回   color   iostream   

使用类计算矩形的面积。定义并实现一个矩形类,有长和宽两个属性,由成员函数计算矩形的面积。矩形类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;

}

技术分享图片

 

类与对象(二)

标签:space   inf   ret   宽度   bubuko   tle   返回   color   iostream   

原文地址:https://www.cnblogs.com/Daylight-Deng/p/10122142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!