0

我尝试在没有模板的情况下编译我的代码,当我添加模板代码时它工作得很好,我收到了 2019LNK 错误。

我在课堂开始时有以下内容:

template<typename T>
friend void inchealth(T &,int);

函数声明:

template<typename T>
void inchealth(T &x, int y)
{x.health += y;}

(健康是我班级的成员变量)

编辑这里是确切的代码:

class archer        
{

template <class T>
friend void inchealth(T &,int);

public:
archer(){health = 150; mana = 50; armor = 50; damage = 10;}

int checkhealth() {return health;}
int checkmana() {return mana;}
int checkarmor() {return armor;}
int checkdamage(){return damage;}


private:
int health;
int mana; 
int armor;
int damage;};

template <class T>
void inchealth(T &x, int y)
{x.health += y;}

void main()
{
archer a;
inchealth(a,5);

}
4

1 回答 1

2

我的心理调试感觉建议您已将 的定义inchealth放在单独的 cpp 文件中以main.

模板化的函数体需要在您调用它们时可见,或者您需要明确告诉编译器实例化您想要的版本。

因此,如果我是正确的,解决方案是将 的定义inchealth从定义的文件移动到标头 #included main,或者添加该行

template void inchealth<archer>(archer&,int);

在定义inchealth它的文件中的定义下方(假设的声明在那里archer可见)。前者是首选。

于 2013-05-27T21:09:43.383 回答