C++类模板分文件

问题:类模板的成员函数是在调用时才被创建,导致分文件编写时调用不到。

解决:

1.直接包含cpp文件

2.将声明和实现写到同一个文件中,并更该后缀名为.hpp,.hpp是约定的名字,并不是强制

(推荐)第二种方式:

头文件:person.hpp

#include<iostream>
using namespace std;

template<class T1, class T2>
class Person {
public:
    Person(T1 name, T2 age);
    void show();
    T1 name;
    T2 age;
};

template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age) {
    this->name = name;
    this->age = age;
}
//对于成员函数,需要指明类的参数的代表
template<class T1, class T2>
void Person<T1, T2>::show() {
    cout << this->name << endl;
    cout << this->age << endl;
}

源文件:test.cpp

//第二种方式,将.h和.cpp中的内容写到一起,将后缀名改为.hpp
#include "person.hpp"


void test() {
    Person<string, int> p("tom", 12);
    p.show();
}

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

将类模板的声明和实现都放在.hpp中,并在cpp文件中进行引用即可。

发布了106 篇原创文章 · 获赞 269 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_32642107/article/details/104777320