• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LOFLY
终其一生,编织快乐
博客园    首页    新随笔    联系   管理    订阅  订阅

C++之类模板的分文件编写问题以及解决

C++之类模板的分文件编写问题以及解决

C++之类模板的分文件编写问题以及解决


建议模板不要分文件编写
image=300

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;
}

Main.cpp文件

#include <iostream>
using namespace std; 
#include "Person.h"

void test01(){
	Person<string,int> p("猪八戒",12);
	p.showPerson();
}

int main()
{
	test01();
	system("pause"); 
	return EXIT_SUCCESS; 
}

运行上面程序会报错,原因是无法解析的外部命令。
解决方法,将main.cpp中的#include "Person.h" 改成#include "Person.cpp".
C++是单元编译的,每个文件单独编译。
因为是模板类,.h文件和.cpp文件链接不到。
image


image
模板的成员函数在运行的时候才会去创建。

posted @ 2022-08-14 10:01  编织快乐  阅读(189)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3