C++ 类模板份文件编写

一、问题:类模板中成员函数创建时机是在调用阶段,导致分文件编写链接不到

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值