初建cpp工程(.h文件和.cpp文件具體內容)

(codeblocks爲例)

1 建一個empty project.

2 在該project下寫 頭文件(.h)和源文件( .cpp)

1)(.h)文件,其中包含:①#define 常數 

    ②類,包括類中成員和方法的聲明(private, public等)

代碼示例:Rectangle.h

#define VALID_MIN 0.0
#define VALID_MAX 20.0
#define DEFAULT_LENGTH 10.0
#define DEFAULT_WIDTH 10.0
#define DEFAULT_PERIMETER 40.0
#define DEFAULT_AREA 100.0


class Rectangle {
public:

    Rectangle();

    float getLength();
    void setLength(float aLength);
    float getWidth();
    void setWidth(float aWidth);

    friend int calculate(Rectangle & aRec1 ); //friend function has access to the private of the object aRec1

private:
    bool validLength(float aLength);          // To judge if rLength of the object is valid.
    bool validWidth(float aWidth);            //To judge if rWidth of the object is valid.
float rLength;                            // rLength, rWidth, perimeter, area are attributes of all Rectangles,
float rWidth;
float perimeter;
float area;
};


2)(.cpp)文件,實現頭文件中已經聲明的方法。

注意:① #include " **.h " (將要實現的頭文件包含在其中)

   ②其他要用到的頭文件也要#include進來。

代碼示例:Rectangle.cpp

#include<iostream>
#include "Rectangle.h"
using namespace std;

Rectangle::Rectangle() : rLength(DEFAULT_LENGTH), rWidth(DEFAULT_WIDTH) {
/* empty */
}


Rectangle::Rectangle(float aLength, float aWidth) : rLength(aLength), rWidth(aWidth) {
}


//Calculate and print perimeter and area of the object.
int calculate(Rectangle & aRec){
}


float Rectangle::getLength() {
return rLength;
}


void Rectangle::setLength(float aLength) {
    if(validLength(aLength))
        rLength = aLength;
    else
        rLength = DEFAULT_LENGTH;
}


float Rectangle::getWidth() {
}


void Rectangle::setWidth(float aWidth) {
}


bool Rectangle::validLength(float aLength) {
}


bool Rectangle::validWidth(float aWidth) {
}


3)建一個main.cpp測試類,其中包含①寫好的(.h)文件

   ② #include<iostream> using namespace std;

main.cpp 代碼示例:

#include<iostream>
#include"Rectangle.h"
using namespace std;


int main()
{
    Rectangle aRec;
    float len,wid;
    cin >> len >> wid;
    aRec.setLength(len);    //users have to use accessors
    aRec.setWidth(wid);     //and mutators to get to the private data in the object


    cout << calculate(aRec) << endl; //friend function print perimeter and area of the object
    return 0;
}

發佈了15 篇原創文章 · 獲贊 10 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章