blog » Dev # 写写代码 » C++ 作业-类-1

C++ 作业-类-1

恩…… 编程太烂了,都是大学里面没好好学。现在慢慢开始学起来,今天写完了第一个 C++ 类的作业,很简单。

题目:

生成一个 Rectangle 类,这个类的 length 和 width 属性默认为 1,其成员函数计算长方形的周长和面积。为该类的 length 和 width 设置 set 和 get 函数。set 函数应该验证 length 和 width 为 0.0-20.0 浮点数。


解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
 
class Rectangle {
        public :
                Rectangle ();
                void get ();
                void setre (double length,double width);
                void printPermeter ();
                void printArea ();
        private :
                double length;
                double width;
                double per;
                double area;
        };
 
#endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//rectangle.cpp
#include <iostream.h>
#include "rectangle.h"
 
 
Rectangle::Rectangle ()
{
        double length = 1;
        double width = 1;
}
 
void Rectangle::get ()
{
        cout << "Length is " << length << endl;
        cout << "Width is " << width << endl;
}
 
void Rectangle::setre (double le,double wi)
{
        length = ( le > 0 && le <= 20) ? le : 1;
        width = ( wi > 0 && wi <= 20 ) ? wi : 1;
}
 
void Rectangle::printPermeter ()
{
        per = length * 2 + width * 2;
        cout << "Permeter is " << per << endl;
}
 
void Rectangle::printArea ()
{
        area = length * width;
        cout << "Area is " << area << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//main.cpp
 
#include <iostream.h>
#include "rectangle.h"
 
int main ()
{
        Rectangle r;
        r.setre ( 3,2 );
        r.printPermeter ();
        r.printArea ();
        r.get ();
 
        return 0;
}

编译:

1
2
g++ -g -c rectangle.cpp -o rectangle.o
g++ main.cpp rectangle.o -o run
RSS 2.0 | leave a response | trackback

发表评论