两个模板函数的使用(C++总结3)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ModestBean/article/details/79562998

说在开头

最近学习到了C++的模板函数的章节,简单来说使用模板函数提高了代码的通用性,不用在考虑数据类型整形(int),还是浮点型(float)。所有的代码都可以在我的github上找到https://github.com/ModestBean/C-Samples ,有什么问题欢迎大家指出。我会接受每一个建议的。

例如

/*整型加法*/
int add(int a,int b){//加法
 return a+b;
}
/*浮点数加法*/
float add(falot a,float b){//加法
 return a+b;
}
int c=add(2,5);//整数相加
float f=add(2.0f,5.0f);//浮点数相加

通过以上的代码我们可以发现,为了实现简单的加法,因为传递的参数的类型不同,我们需要去定义两个参数不同的方法。这同时也是程序员不想看到的。

代码部分

单个cpp文件中的使用

#include <iostream>
template <class T>
T add(T a, T b) {//加法函数
    return a + b;
}
int main() {
    int i1 = add(1, 2);
    float f2 = add(3.3f, 4.2f);
    std::cout << i1 << "||" << f2 << std::endl;
    std::cin.get();
    /*所得结果û 3||7.5*/
}

这是一个简单的模板函数的使用,这里我只在一个cpp文件中完成了相应的定义和使用,我们在开发过程中肯定不会只使用一个源文件的,还会和头文件联合使用。

与.h文件一起使用的例子

TemplateSample.h

template <typename T>
class TemplateSample
{
public:
    TemplateSample(T widthIn, T heightIn)
        : width(widthIn),height(heightIn)
    {
    }
    T CalculateArea() {//计算面积
        return width*height;
    }
private:
    T width;//宽度
    T height;//高度
};

main.cpp

#include <iostream>
#include "TemplateSample.h"
using namespace std;
int main() {
    TemplateSample<int > s1(1,2);
    int area=s1.CalculateArea();
    cout << "计算出的面积是" << area << endl;
    std::cin.get();
}

这和头文件联合使用的。

尚未解决的问题

  • template <class T> template <typename T> 定义中两个类型class和typename不知道其正确的含义。
  • 在头文件中定义函数后,在对应的实现文件(.cpp)中为什么不能够在使用构造函数和析构函数了,这个我也不是特别理解。
    希望大家能帮我解决这两个小问题。

                    MBean。 
    

猜你喜欢

转载自blog.csdn.net/ModestBean/article/details/79562998