C++ namespace的用法


//namesp.h
namespace pers{
    const int LEN = 40;
    struct Person{
        char fname[LEN];
        char lname[LEN];
    };
    void getPerson(Person &);
    void showPerson(const Person &);
}

namespace debts{
    using namespace pers;
    struct Debt{
        Person name;
        double amount;
    };
    void getDebt(Debt &);
    void showDebt(const Debt &);
    double sumDebts(const Debt ar[], int n);
}

 

第二個文件:

//namesp.cpp
#include <iostream>
#include "namesp.h"

namespace pers{
    using std::cout;
    using std::cin;
    void getPerson(Person &rp){
        cout<<"Enter first name: ";
        cin>>rp.fname;
        cout<<"Enter last name: ";
        cin>>rp.lname;
    }
    
    void showPerson(const Person &rp){
        cout<<rp.lname<<", "<< rp.fname;
    }
}


namespace debts{
    using std::cout;
    using std::cin;
    using std::endl;
    
    void getDebt(Debt & rd){
        getPerson(rd.name);
        cout<< "Enter debt: ";
        cin>>rd.amount;
    }
    
    void showDebt(const Debt &rd){
        showPerson(rd.name);
        cout<<": $"<<rd.amount<<endl;
    }
    
    double sumDebts(const Debt ar[], int n){
        double total  = 0;
        for(int i = 0; i < n; i++){
            total += ar[i].amount;
        }
        
        return total;
    }
}

第三個文件:

//namessp.cpp
#include <iostream>
#include "namesp.h"

void other (void);
void another(void);

int main(void)
{
    using debts::Debt;
    using debts::showDebt;
    Debt golf = { {"Benny","Goatsniff"},120.0};
    showDebt(golf);
    other();
    another();
    
    return 0;
}


void other(void)
{
    using std::cout;
    using std::endl;
    
    using namespace debts;
    Person dg = {"Doodle", "Glister"};
    showPerson(dg);
    cout<<endl;
    Debt zippy[3];
    int i;
    
    for(i = 0; i < 3; i++){
        getDebt(zippy[i]);
    }
    
    for(i = 0; i < 3; i++){
        showDebt(zippy[i]);
    }
    
    cout<<"Total  debt: $" <<sumDebts(zippy,3)<<endl;
    return;
}

void another(void){
    using pers::Person;
    
    Person collector = {"Milo", "Rightshift"};
    pers::showPerson(collector);
    std::cout<<std::endl;
}

 

C++鼓勵程序員在開發程序時使用多個文件.一種有效的組織策略是,使用頭文件來定義用戶類型,為操縱用戶類型 的函數 提供函數原型;並將函數 定義放在一個獨立的源代碼當中.頭文件和源代碼文件一起定義和實現了用戶定義的類型 及其使用方式.最后,將main()和其他這些函數的函數放在第三個文件中.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM