c++將檔案之間編譯關係降到最低

來源:互聯網
上載者:User

標籤:

類的定義式:類的定義,可以知道類的大小

類的實現:

類的聲明:類的聲明,表明,使用此類,編譯不會出錯

C++並沒有把“將介面從實現中分離”做得很好。Class的定義式不只詳細敘述了Class介面,還包括十足的實現序幕。如:

class Person

{

  public:

     Person(const string& name,const Dateg& birthday,const Address& addr);

     string name() const;

     string birthDate() const;

     string address() const;

     ....

 private:

    string theName;

    Date  thebirthDate;

    Address theAddress; 

};                                

 

   這裡的Person無法通過編譯,因為編譯器沒看到string,Date和Address的定義式。這樣的定義式通常由#include指示符提供,所以Person定義檔案的最上方很可能存在這樣的東西:

#include  <string>

#include “date.h”

#include “address.h”

   但是,這麼一來便是在Person定義檔案和其含入檔案之間形成了一種編譯依存關係。如果這些標頭檔中的一個被改變,或這些標頭檔所依賴的其他標頭檔有任何改變,那麼每一個含入Person class的檔案就得重新編譯,任何使用Person class的檔案也必須重新編譯。這通常會對大項目造成災難。

解決方案:

考慮加上前置聲明,以去掉#include包含的標頭檔:

class Date;//前置聲明 
class Address;//前置聲明 
class Person{ 
public: 
    Person(const std::string& name, const Date& birthday, const Address& addr); 
    std::string name() const; 
    std::string birthDate() const; 
    std::string address() const; 
    ... 

private:        //可有可無,隨便寫不寫

     string theName;

    Date  thebirthDate;

    Address theAddress; 


};

通過此方法,可以消除耦合,class person與class Date等沒有依賴關係,Person的客戶就只有在Person介面被修改時才重新編譯。

但是這個方法有個問題:

int main(){    int x;    Person p(params);}
當編譯器看到x的定義式,它知道必須分配多少記憶體才能夠容下一個int。但當編議器看到p的定義式,如何知道一個person有多大?唯一的辦法就是詢問class的定義式,然而如果class定義式不列出實現的細節(不知道到class Date等的實現細節)

c++將檔案之間編譯關係降到最低

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.