c++类模板分文件编写存在的问题

c++分文件编写的编译机制:

       各个文件独立编译,如果在某.cpp文件中出现了函数调用,但是在此.cpp文件并没有对应函数的实现。此时就会在函数调用出生成特定的符号,在之后的链接过程完成函数调用。

C++模板的编译机制:

       模板都会进行两次编译。当编译器第一次遇到模板时进行一次普通的编译,当调用函数模板时进行第二次编译。第二次编译将特定值带入编译如:

在分文件编写类模板,不调用时。编译是不会出现问题的。如下:

Car.h文件

 1 #ifndef _CAR_H
 2 #define _CAR_H
 3 
 4 
 5 template<class T>
 6 class Car{
 7 public:
 8     Car(T c);
 9     ~Car();
10     T GetColor();
11 private:
12     T Color;//颜色
13 };
14 
15 #endif

 Car.cpp文件

#include"Car.h"
#include <iostream>
#include <string>

using namespace std;

template<class T>
Car<T>::Car(T c)
{

    this->Color = c;
}

template<class T>
Car<T>::~Car()
{
    cout << "~Car___析构函数" << endl;
}

template<class T>
T Car<T>::GetColor()
{
    return this->Color;
}

mian.cpp文件

#include <iostream>
#include <string>
#include "Car.h"

using namespace std;

int main()
{
    //没有调用类模板
    system("pause");
    return 0;
}

在没用调用类模板的情况下编译:(成功,这也很好的证明C++分文件编译的机制)

如果将main.cpp改为如下情况在编译:

#include <iostream>
#include <string>
#include "Car.h"

using namespace std;

int main()
{
    Car<string>car("red");
    car.GetColor();
    system("pause");
    return 0;
}

在调用模板的情况编译:(失败,在main.cpp中调用了string GetColor()函数,在main.cpp中并没有该函数而且在其他文件中也没此函数)

解决方法:

     1.将Car.cpp改为Car.hpp

     2.将#include"Car.h"改为#include“Car.hpp”

 

原文地址:https://www.cnblogs.com/lovemee/p/10706061.html