C++基础知识 - 类模板函数写在类的外部

2023-10-27

1. 所有的类模板函数写在类的外部,在一个cpp中

#include <iostream>
#include <Windows.h>
using namespace std;

template <typename T>
class Demo {
public:
	Demo(T data = 0);	//构造函数
	Demo operator+(const Demo& other);	//对象的data相加,返回一个对象
	T getData() const;	//获取data
private:
	T data;
};

//在类的实现文件里,需要声名类模板
template <typename T>
//类的作用域前添加<T>
Demo<T>::Demo(T data) {
	this->data = data;
}

template <typename T>
//类的返回值,类的作用域,类的形参都需要添加模板声明
Demo<T> Demo<T>::operator+(const Demo<T>& other) {
	Demo tmp;
	tmp.data = (this->data + other.data);
	return tmp;
}

template <typename T>
T Demo<T>::getData() const {
	return this->data;
}


int main(void) {
	Demo<int> d1(100), d2(200);

	Demo<int> tmp = d1 + d2;

	cout << tmp.getData() << endl;

	system("pause");
	return 0;
}

总结:

在同一个cpp 文件中把模板类的成员函数放到类的外部,需要注意以下几点

  • 函数前声明 template <类型形式参数表>
  • 类的成员函数前的类限定域说明必须要带上虚拟参数列表
  • 返回的变量是模板类的对象时必须带上虚拟参数列表
  • 成员函数参数中出现模板类的对象时必须带上虚拟参数列表
  • 成员函数内部没有限定

 
 

2. 所有的类模板函数写在类的外部,在不同的.h和.cpp中

需要在类模板时 包含#include “Demo.cpp” //需要包含类的实现.cpp文件

Demo.h

#pragma once

template <typename T>
class Demo{
public:
	Demo(T data = 0);	//构造函数
	Demo operator+(const Demo& other);	//对象的data相加,返回一个对象
	T getData() const;	//获取data
private:
	T data;
};

Demo.cpp

#include "Demo.h"

//在类的实现文件里,需要声名类模板
template <typename T>
//类的作用域前添加<T>
Demo<T>::Demo(T data){
	this->data = data;
}

template <typename T>
//类的返回值,类的作用域,类的形参都需要添加模板声明
Demo<T> Demo<T>::operator+(const Demo<T>& other){
	Demo tmp;
	tmp.data = (this->data + other.data);
	return tmp;
}

template <typename T>
T Demo<T>::getData() const{
	return this->data;
}

main.cpp

#include <iostream>
#include <Windows.h>
#include "Demo.cpp"	//需要包含类的实现.cpp文件
#include "Demo.h"
using namespace std;

int main(void) {
	Demo<int> d1(100), d2(200);

	Demo<int> tmp = d1 + d2;

	cout << tmp.getData() << endl;

	system("pause");
	return 0;
}

注意:

当类模板的声明(.h文件)和实现(.cpp 或.hpp文件)完全分离,因为类模板的特殊实现,我们应在使用类模板时使用#include 包含 实现部分的.cpp 或.hpp文件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++基础知识 - 类模板函数写在类的外部 的相关文章

随机推荐