类模板分文件编写

问题:

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

解决:

方式1:将声明和实现写到同一个文件中,并更名后缀为.hpp,hpp是约定的名称,并不是强制的。

方式2:直接包含.cpp源文件(不推荐)

person.h文件的代码:

cpp 复制代码
#pragma once
#include <iostream>

using namespace std;

template<typename T1, typename T2>
class Person
{
public:
	T1 m_Name;
	T2 m_Age;

	Person(T1 name, T2 age);

	void showPerson();
};

person.cpp文件的代码:

cpp 复制代码
#include <iostream>
#include "person.h"

// 构造函数的实现
template<typename T1, typename T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
	m_Name = name;
	m_Age = age;
}

// 成员函数的实现
template<typename T1, typename T2>
void Person<T1, T2>::showPerson()
{
	cout << "姓名:" << m_Name << " 年龄:" << m_Age << endl;
}

main.cpp中的代码:

cpp 复制代码
#include <iostream>
#include <Windows.h>
#include <string>

#include "person.h"

using namespace std;

void test()
{
	Person<string, int> p("张三", 18); // 报错:无法解析的外部命令
	p.showPerson(); // 报错:无法解析的外部命令
}


int main(void)
{
	test();
	
	system("pause");
	return 0;
}

执行这两行代码Person<string, int> p("张三", 18); p.showPerson(); 的时候,报错:无法解析的外部命令。

解决方式1:

person.hpp中的代码:

cpp 复制代码
#pragma once
#include <iostream>

using namespace std;

template<typename T1, typename T2>
class Person
{
public:
	T1 m_Name;
	T2 m_Age;

	Person(T1 name, T2 age);

	void showPerson();
};

// 构造函数的实现
template<typename T1, typename T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
	m_Name = name;
	m_Age = age;
}

// 成员函数的实现
template<typename T1, typename T2>
void Person<T1, T2>::showPerson()
{
	cout << "姓名:" << m_Name << " 年龄:" << m_Age << endl;
}

main.cpp中的代码:

cpp 复制代码
#include <iostream>
#include <Windows.h>
#include <string>

#include "person.hpp" // 将声明和实现写到同一个文件中,并更名后缀为.hpp

using namespace std;

void test()
{
	Person<string, int> p("张三", 18); 
	p.showPerson();
}


int main(void)
{
	test();
	
	system("pause");
	return 0;
}

解决方式2:

cpp 复制代码
#include <iostream>
#include <Windows.h>
#include <string>

#include "person.cpp" // 包含.cpp源文件

using namespace std;

void test()
{
	Person<string, int> p("张三", 18); 
	p.showPerson();
}


int main(void)
{
	test();
	
	system("pause");
	return 0;
}
相关推荐
4U2471 个月前
C++中的string的介绍(从string到STL)
开发语言·数据结构·c++·stl·string·类模板
GeniusAng丶3 个月前
C++模板编程—学习C++类库的编程基础
c++·stl·类模板·函数模版
韩曙亮10 个月前
【C++】泛型编程 ⑭ ( 类模板示例 - 数组类模板 | 容器思想 | 自定义类可拷贝 - 深拷贝与浅拷贝 | 自定义类可打印 - 左移运算符重载 )
开发语言·c++·类模板·泛型编程·数组类模板
program-learner10 个月前
C++模板初阶
c++·模板·函数模板·类模板·泛型编程
忆梦初心1 年前
【C++深入浅出】模版初识
c++·函数模板·类模板·泛型编程