目录
1.所有的类模板函数写在类的内部
直接类中开撸~
2.类模板的函数实现与类在同一个cpp文件
在同一个cpp文件中把类模板类的成员函数放到类的外部,需要注意以下几点:
1.函数前声明 template <类型形式参数表>2.类的成员函数前的 类作用域 必须带上虚拟参数列表
3.返回变量是模板类的对象时,必须带上虚拟参数列表
4.成员函数参数中出翔模板类的对象时必须带上虚拟参数列表
4.成员函数内部没有限定
#include<iostream>
using namespace std;
template<typename T>
class A {
public:
A(T t=0);
T& getT();
A operator+(const A& other);
void print();
private:
T t;
};
template <typename T>
A<T>::A(T t) {
this->t = t;
}
template<typename T>
T &A<T>::getT() {
returh t;
}
template <typename T>
A<T> A<T>::operator+(const A<T>& other) {
A<T> temp;//类的内部类型可以显示声明,也可以不显示
temp.t = other.t;
return temp;
}
template <typename T>
void A<T>::print() {
return this->t;
}
3.类模板函数写在类的外部,在不同的.h和.cpp中
demo.h文件中
template<typename T>
class A {
public:
A(T t=0);
T& getT();
A operator+(const A& other);
void print();
private:
T t;
};
demo .cpp文件
#include"demo.h"
template <typename T>
A<T>::A(T t) {
this->t = t;
}
template<typename T>
T &A<T>::getT() {
returh t;
}
template <typename T>
A<T> A<T>::operator+(const A<T>& other) {
A<T> temp;//类的内部类型可以显示声明,也可以不显示
temp.t = other.t;
return temp;
}
template <typename T>
void A<T>::print() {
return this->t;
}
没有区别~