2013-07-28 19 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)模板,其实现取决于传递给他们的参数。

相关问题