2013-07-28 24 views
0

寧可自我解釋。我只是想知道在面向對象的C++中做什麼更傳統?在C++中,定義類定義內部還是外部的方法體更爲常規?

實例A:

class CarObject{ 
private:       //Local Variables 
    string name;  
    int cost; 
public: 
    CarObject(string pName, int pCost){  //Constructor with parameters of car name and car cost 
     name = pName;   //Sets the temporary variables to the private variables 
     cost = pCost; 
    }  
    void getDetails(){ 


      cout << name; 
      cout << cost; 

      }//Public method that returns details of Car Object 
}; 

例B:

class CarObject{ 
private:       //Local Variables 
    string name;  
    int cost; 
public: 
    CarObject(string pName, int pCost){  //Constructor with parameters of car name and car cost 
     name = pName;   //Sets the temporary variables to the private variables 
     cost = pCost; 
    }  
    void getDetails(); //Public method that returns details of Car Object 
}; 
void CarObject :: getDetails(){ 
    cout << name; 
    cout << cost; 
} 
+2

外面,除非模板化。 – ChiefTwoPencils

+0

你有沒有看過任何C++代碼?遍及互聯網和每本C++書籍和教程都有例子。 –

+0

這同樣適用於構造函數嗎? –

回答

3

您的類定義通常是在.h文件中,而你的方法等實施細節將在.cpp文件。這允許在管理依賴關係時具有最大的靈活性,在更改實現時防止不必要的重新編譯,並且是大多數編譯器和IDE期望的模式。

主要的例外情況是:(1)inline函數,它應該簡短/簡單,編譯器可以選擇插入來代替實際的函數調用;(2)模板,其實現取決於傳遞給他們的參數。

相關問題