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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值