一.问题:
类模板中,成员函数创建时机是在调用阶段,这会导致分文件编写时连接不到
二.解决:
解决方式1:直接包含.cpp源文件
解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称, 并不是强制
1. 直接包含.cpp源文件:
Person.h
#pragma once
#include<iostream>
template<class T1, class T2>
class Person
{
public:
//成员函数类内声明
Person(T1 name, T2 age);
void ShowPerson();
T1 MyName;
T2 MyAge;
};
Person.cpp
#include "Person.h"
#include<string>
using namespace std;
//构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->MyName = name;
this->MyAge = age;
}
//成员函数类外实现
template<class T1, class T2>
void Person<T1, T2>::ShowPerson()
{
cout << "姓名:" << this->MyName << "\t年龄:" << this->MyAge << endl;
}
main.cpp
#include<iostream>
#include<string>
#include "Person.cpp" //直接包含Person.cpp源文件
using namespace std;
void test()
{
Person<string, int> p("Tom",20);
p.ShowPerson();
}
int main()
{
test();
return 0;
}
运行结果:
姓名:Tom 年龄:20
2.将声明和实现写到同一个文件中,并更改后缀名为.hpp:
Person.hpp
#include<iostream>
#include<string>
using namespace std;
template<class T1, class T2>
class Person
{
public:
//成员函数类内声明
Person(T1 name, T2 age);
void ShowPerson();
T1 MyName;
T2 MyAge;
};
//构造函数类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->MyName = name;
this->MyAge = age;
}
//成员函数类外实现
template<class T1, class T2>
void Person<T1, T2>::ShowPerson()
{
cout << "姓名:" << this->MyName << "\t年龄:" << this->MyAge << endl;
}
main.cpp
#include<iostream>
#include<string>
#include "Person.hpp"
using namespace std;
void test()
{
Person<string, int> p("Tom",20);
p.ShowPerson();
}
int main()
{
test();
return 0;
}
运行结果:
姓名:Tom 年龄:20
三.总结:
一般用第二种方法写分文件,将类模板成员函数写到一起,并将后缀名改为.hpp