您的位置:首页 > 编程语言 > C语言/C++

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

2019-04-14 17:38 627 查看

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

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

C++模板的编译机制:

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

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

Car.h文件

#ifndef _CAR_H
#define _CAR_H

template<class T>
class Car{
public:
Car(T c);
~Car();
T GetColor();
private:
T Color;//颜色
};

#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”

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐