在类模板类外实现.h和.cpp分来写的时候
//Person.h
#pragma once
template<class T>
class Person {
public:
Person(T age);
void show();
T age;
};
//Person.cpp
#include "stdafx.h"
#include"Person.h"
template<class T>
Person<T>::Person(T age)
{
this->age = age;
}
template<class T>
void Person<T>::show()
{
cout << "age=" << age << endl;
}
// 类外实现分开写1.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
#include"Person.h"
int main()
{
Person<int> p(10);
p.show();
return 0;
}
严重性 代码 说明 项目 文件 行 禁止显示状态
错误 LNK2019 无法解析的外部符号 “public: __thiscall Person::Person(int)” (??0?KaTeX parse error: Undefined control sequence: \Users at position 49: …被引用 类外实现分开写1 c:\̲U̲s̲e̲r̲s̲\lfzh\source\re…Person@H@@QAEXXZ),该符号在函数 _main 中被引用 类外实现分开写1 c:\Users\lfzh\source\repos\排序\类外实现分开写1\类外实现分开写1.obj 1
这种情况和模板实现机制,c++编译机制有关
解决办法
将#include"Person.h"
改为#include"Person.cpp"
所以类模板一半不要分开写 将.cpp改为.hpp
#include"Person.hpp"