问题: 类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到
解决:
解决方式1:直接包含.cpp源文件
解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制
普通写法:
#include<iostream>
using namespace std;//类模板分文件编写的问题以及解决
#include<string>
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)
{this->m_Name = name;this->m_Age = age;
}template<class T1, class T2>
void Person<T1, T2>::showPerson()
{cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl;
}void test()
{Person <string, int>p("Jerry", 20);p.showPerson();
}int main()
{test();return 0;
}
问题:分文件编写中,在类模板分文件编写.cpp中包含person.h头文件仍然出错!
解决方式1:直接包含.cpp源文件
创建person.h添加以下代码:
#pragma once
#include<iostream>
using namespace std;#include<string>
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)
{this->m_Name = name;this->m_Age = age;
}template<class T1, class T2>
void Person<T1, T2>::showPerson()
{cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl;
}
类模板分文件编写.cpp中:
#include<iostream>
using namespace std;//第一种解决方式,直接包含源文件
#include "person.cpp"//将这行的#include "person.h"改为#include "person.cpp"void test()
{Person <string, int>p("Jerry", 20);p.showPerson();
}int main()
{test();return 0;
}
解决方式2:将.h和.cpp中的内容写到一起,将后缀名改为.hpp文件(常用)
创建person.hpp添加以下代码:
#pragma once
#include<iostream>
using namespace std;#include<string>
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)
{this->m_Name = name;this->m_Age = age;
}template<class T1, class T2>
void Person<T1, T2>::showPerson()
{cout << "姓名: " << this->m_Name << " 年龄: " << this->m_Age << endl;
}
类模板分文件编写.cpp中:
#include<iostream>
using namespace std;//包含hpp头文件
#include "person.hpp"void test()
{Person <string, int>p("Jerry", 20);p.showPerson();
}int main()
{test();return 0;
}
总结:主流的解决方式是第二种,将类模板成员函数写到一起,并将后缀名改为.hpp