C++ 学习之类模板分文件编写的注意事项

1、抛出问题

按照常规的分文件编写方式,.h文件里写类的声明,.cpp文件写类的实现,最后在总的cpp文件中包含.h文件,编译运行。即下面这种写法,使用了类模板会出现问题:

person.h中写类的声明:
#ifndef _PERSON_H_
#define _PERSON_H_

template<class T1, class T2>
class Person
{
public:
	Person(T1 name, T2 age);//默认构造函数声明

	void ShoePerson();//成员函数声明

private:

	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>::ShoePerson()//类外成员函数实现
{
	cout << "姓名:" << this->m_name << " " << "年龄:" << this->m_age << endl;
}
*/


#endif // !_PERSON_H_

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>::ShoePerson()//类外成员函数实现
{
	cout << "姓名:" << this->m_name << " " << "年龄:" << this->m_age << endl;
}
总的cpp文件中写具体调用:
#include<iostream>
#include<string>
#include"person.h"
using namespace std;


int main()
{
	Person<string, int> p("孙悟空", 100);
	return 0;
}

这时候编译运行就出问题了,报错:一个无法解析的外部命令,即Person这个数据类型。
为啥呢?
因为含有类模板的文件比较特殊,跟普通文件不一样,普通类中的成员函数一开始就创建好了,等调用的时候编译器也可以找到;
但类模板中成员函数创建时机是在调用阶段,主文件中只包含了.h文件,说明只让编译器看到了声明的文件,没有看到具体实现的函数;而在调用的时候,编译器无法创建具体实现函数,就会出错了,导致分文件编写时链接不到。

解决方法两种:
  • 直接包含.cpp源文件,这时候编译器看到了具体函数实现,又通过源文件中包含的.h看到了声明,调用就没有问题了。但是这种方法用的不多,主要是与通常的逻辑不一样,一般都是包含.h,但是在类模板里却包含了.cpp,这就让人很不好理解;
  • 把声明和实现写在同一个文件里,文件名字改为 .hpp,这是约定俗成的一种方法,并不是强制,使用的很广泛,.hpp的后缀名让人一眼就能知道是包含类模板的头文件。

2、 正确实现(类模板声明实现写到一起,并将后缀名改为.hpp)

person.hpp :
#ifndef _PERSON_HPP_
#define _PERSON_HPP_

template<class T1, class T2>
class Person
{
public:
	Person(T1 name, T2 age);//默认构造函数声明

	void ShoePerson();//成员函数声明

private:

	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>::ShoePerson()//类外成员函数实现
{
	cout << "姓名:" << this->m_name << " " << "年龄:" << this->m_age << endl;
}



#endif // !_PERSON_H_

主cpp :
#include<iostream>
#include<string>
#include"person.hpp"//包含.hpp文件
using namespace std;


int main()
{
	Person<string, int> p("孙悟空", 100);
	p.ShoePerson();
	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值