2014-01-21 132 views
0

!我工作的一炮模板,它應該是這樣的:使用類作爲模板類型

template <Bullet> 
class gun 
{ 



}; 

那子彈是一個類,將在其他文件中定義,我的問題是如何在槍使用子彈作爲一種類型?我怎樣才能將一個類用作其他類的模板?我想要一點點長解釋! 謝謝...!

這就是我試圖做的:

#include "Bullet.h" 
#include <iostream> 
using namespace std; 
#define BulletWeapon1 100 
#define BulletWeapon2 30 
#define BulletWeapon3 50 
enum Weapons 
{ 
    Gun1,Gun2,Gun3 

}CurrentWeapon; 
template <class T=Bullet> 
class Gun 
{ 



}; 

int main() 
{ 
    return 0; 
} 

回答

0

如果您只需要需要Bullet類中gun,那麼你可以不使用模板:

class gun { 
    Bullet x; 
    // ... 
}; 

否則,如果您想允許任何班級提供默認班級Bullet,您可以使用:

template <class T = Bullet> 
class gun { 
    T x; 
    // ... 
}; 

特別是,如果您想確保T始終是基類Bullet,您可以玩類型特徵,如std::enable_ifstd::is_base_of


在一個側面說明,請儘量避免之類的語句using namespace std;,並開始逐漸適應std::前綴來代替。當您遇到多種定義或奇怪的查找問題時,它會爲您節省一些麻煩。

此外,請儘量避免#define s。這:

#define BulletWeapon1 100 
#define BulletWeapon2 30 
#define BulletWeapon3 50 

可以轉換爲:

const int BulletWeapon1 = 100; 
const int BulletWeapon2 = 30; 
const int BulletWeapon3 = 50; 

最後請注意,在C++ 11可以使用enum class ES這是多一點點型不是簡單enum的保險櫃:

enum Weapons { Gun1,Gun2,Gun3 } CurrentWeapon; 

可以成爲:

enum class Weapons { Gun1, Gun2, Gun3 } CurrentWeapon = Weapons::Gun1; 
+0

謝謝...! 我在我的課堂上定義了一個來自T的X,但是我可以'使用任何Bullet方法! 我定義我的模板類是這樣的: Gun g; 那現在有什麼問題?! –

+0

@PeymanTahghighi「我在課堂上定義了一個來自T的X,但我不能使用任何Bullet方法!」 - 我很努力去理解。你可以發佈非工作代碼[here](http://coliru.stacked-crooked.com/)並點擊「Share!」並通過鏈接給我? – Shoe

+0

#包括「Bullet1。h」的使用命名空間std 的#include ; 的#define BulletWeapon1 100 的#define BulletWeapon2 30 的#define BulletWeapon3 50個 枚舉武器 { \t Gun1,Gun2,Gun3 } CurrentWeapon; 模板 類槍 { }; INT主() { \t槍克; \t返回0; } –

相關問題