zoukankan      html  css  js  c++  java
  • c++之类模板分文件编写

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

    解决

    1.直接包含cpp文件

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

    第一种方式

    头文件:person.h

    #include<iostream>
    using namespace std;
    
    template<class T1, class T2>
    class Person {
    public:
        Person(T1 name, T2 age);
        void show();
        T1 name;
        T2 age;
    };

    源文件:person.cpp

    #include "person.h"
    
    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

    //第一种方式,直接包含源文件
    #include "person.cpp"
    
    void test() {
        Person<string, int> p("tom", 12);
        p.show();
    }
    
    int main() {
        test();
        system("pause");
        return 0;
    }

    注意标红的地方,引入的是person.cpp,而不是person.h,因为类模板成员函数是在调用时才创建的,因此在编译阶段引入person.h是找不到声明的实现的。

    第二种方式:

    头文件: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文件中进行引用即可。

  • 相关阅读:
    【面试】代码默写-DCL单例
    【状态机】SCXML2
    【面试】JVM
    【面试】HashMap
    读取resource下sql脚本并执行
    Maven 二进制资源文件(excel pdf...)部署出错,乱码的解决方案
    【JVM】java内存模型
    【Spring】源码二、IOC
    mapstruct 高级用法
    warning: The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 6.0, but the range of supported deployment target versions is 8.0 to 13.2.99.
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12107823.html
Copyright © 2011-2022 走看看