[C++] 程序模块组织

头文件:结构(包括类)的声明以及使用该结构的方法的原型(或许还包括模板声明、内联函数、符号常量);

源文件:与结构(包括类)相关的方法的实现;

源文件:调用方法;

以上是C++程序的模块基本组织策略,在另一个程序中,当需要使用这些方法,则只需要包含头文件同时把方法实现文件添加到工程中或者make的路径中即可。注意尽量不要把方法的实现放到头文件中,如果那么做了,如果该头文件在同一个程序中被包含多次,则该方法在程序中就被实现了多次,显然是不允许的(除非是内联函数)!

//**********coordin.h*************
#ifndef COORDIN_H
#define COORDIN_H

struct polar
{
    double distance;
    double angle;
};

struct rect
{
    double x;
    double y;
};

polar rect_to_polar(rect rct);
void show_polar(polar pl);

#endif  //COORDIN_H


//**********coordin.cpp*************
#include <iostream>
#include "coordin.h"
#include <cmath>
using namespace std;

polar rect_to_polar(rect rct)
{
    polar ret;

    ret.distance = sqrt(rct.x * rct.x + rct.y *rct.y);
    ret.angle = atan2(rct.y, rct.x);

    return ret;
}

void show_polar(polar pl)
{
    const double rad_to_deg = 57.29577951;

    cout<<"distance:"<<pl.distance;
    cout<<", angle:"<<pl.angle * rad_to_deg;
    cout<<" degrees\n";
}

//**********main.cpp*************
#include <iostream>
#include "coordin.h"
using namespace std;

int main()
{
    rect rct;
    polar pl;
    cout<<"enter x & y:\n";
    while(cin>>rct.x>>rct.y)
    {
        pl = rect_to_polar(rct);
        show_polar(pl);
        cout<<"next two numbers:";
    }
    cout << "bye!\n";
    return 0;
}

 

posted @ 2018-03-29 15:35  ingy  阅读(827)  评论(0编辑  收藏  举报