一、问题:类模板中成员函数创建时机是在调用阶段,导致分文件编写链接不到
1、分文件编写前:
#include<iostream>
using namespace std;
template<class T1,class T2>
class person
{
public:
person(T1 name,T2 age);
void showPerson();
T1 m_name;
T2 m_age;
};
template<class T1,class T2>
person<T1, T2>::person(T1 name, T2 age)
{
m_name = name;
m_age = age;
}
template<class T1,class T2>
void person<T1, T2>::showPerson()
{
cout << "名字:" << m_name << " " << "年龄:" << m_age<< endl;
}
int main()
{
person<string,int>p("悟空",18);
p.showPerson();
return 0;
}
程序可以正常运行
2、分文件编写后:
头文件:person.h (声明类成员函数)
#pragma once //防止头文件重复包含
#include<iostream>
using namespace std;
template<class T1, class T2>
class person
{
public:
person(T1 name, T2 age);
void showPerson();
T1 m_name;
T2 m_age;
};
person.cpp(定义成员函数)
#include"person.h"
template<class T1, class T2>
person<T1, T2>::person(T1 name, T2 age)
{
m_name = name;
m_age = age;
}
template<class T1, class T2>
void person<T1, T2>::showPerson()
{
cout << "名字:" << m_name << " " << "年龄:" << m_age << endl;
}
运行主程序:(运行结果报错,无法解析外部命令)
#include<iostream>
using namespace std;
#include"person.h"
int main()
{
person<string,int>p("悟空",18);
p.showPerson();
return 0;
}
二、解决方法:
1、直接包含源文件(将主程序中包含的头文件改为源文件.cpp)
#include<iostream>
using namespace std;
#include"person.cpp"
2、将.h和.cpp中的内容写在一起,将后缀名改为.hpp。
person.hpp
#pragma once //防止头文件重复包含
#include<iostream>
using namespace std;
template<class T1, class T2>
class person
{
public:
person(T1 name, T2 age);
void showPerson();
T1 m_name;
T2 m_age;
};
template<class T1, class T2>
person<T1, T2>::person(T1 name, T2 age)
{
m_name = name;
m_age = age;
}
template<class T1, class T2>
void person<T1, T2>::showPerson()
{
cout << "名字:" << m_name << " " << "年龄:" << m_age << endl;
}
主程序:
#include<iostream>
using namespace std;
#include"person.hpp"
int main()
{
person<string,int>p("悟空",18);
p.showPerson();
return 0;
}