2014-01-21 161 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; } –

相关问题