1、抛出问题
按照常规的分文件编写方式,.h文件里写类的声明,.cpp文件写类的实现,最后在总的cpp文件中包含.h文件,编译运行。即下面这种写法,使用了类模板会出现问题:
person.h中写类的声明:
#ifndef _PERSON_H_
#define _PERSON_H_
template<class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age);//默认构造函数声明
void ShoePerson();//成员函数声明
private:
T1 m_name;
T2 m_age;
};
/*
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)//类外构造函数实现
{
this->m_name = name;
this->m_age = age;
}
template<class T1, class T2>
void Person<T1, T2>::ShoePerson()//类外成员函数实现
{
cout << "姓名:" << this->m_name << " " << "年龄:" << this->m_age << endl;
}
*/
#endif // !_PERSON_H_
person.cpp中写类的实现:
#include"person.h"
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)//类外构造函数实现
{
this->m_name = name;
this->m_age = age;
}
template<class T1, class T2>
void Person<T1, T2>::ShoePerson()//类外成员函数实现
{
cout << "姓名:" << this->m_name << " " << "年龄:" << this->m_age << endl;
}
总的cpp文件中写具体调用:
#include<iostream>
#include<string>
#include"person.h"
using namespace std;
int main()
{
Person<string, int> p("孙悟空", 100);
return 0;
}
这时候编译运行就出问题了,报错:一个无法解析的外部命令,即Person这个数据类型。
为啥呢?
因为含有类模板的文件比较特殊,跟普通文件不一样,普通类中的成员函数一开始就创建好了,等调用的时候编译器也可以找到;
但类模板中成员函数创建时机是在调用阶段,主文件中只包含了.h文件,说明只让编译器看到了声明的文件,没有看到具体实现的函数;而在调用的时候,编译器无法创建具体实现函数,就会出错了,导致分文件编写时链接不到。
解决方法两种:
- 直接包含.cpp源文件,这时候编译器看到了具体函数实现,又通过源文件中包含的.h看到了声明,调用就没有问题了。但是这种方法用的不多,主要是与通常的逻辑不一样,一般都是包含.h,但是在类模板里却包含了.cpp,这就让人很不好理解;
- 把声明和实现写在同一个文件里,文件名字改为 .hpp,这是约定俗成的一种方法,并不是强制,使用的很广泛,.hpp的后缀名让人一眼就能知道是包含类模板的头文件。
2、 正确实现(类模板声明实现写到一起,并将后缀名改为.hpp)
person.hpp :
#ifndef _PERSON_HPP_
#define _PERSON_HPP_
template<class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age);//默认构造函数声明
void ShoePerson();//成员函数声明
private:
T1 m_name;
T2 m_age;
};
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)//类外构造函数实现
{
this->m_name = name;
this->m_age = age;
}
template<class T1, class T2>
void Person<T1, T2>::ShoePerson()//类外成员函数实现
{
cout << "姓名:" << this->m_name << " " << "年龄:" << this->m_age << endl;
}
#endif // !_PERSON_H_
主cpp :
#include<iostream>
#include<string>
#include"person.hpp"//包含.hpp文件
using namespace std;
int main()
{
Person<string, int> p("孙悟空", 100);
p.ShoePerson();
return 0;
}