C++模板(一)

在vs2015中,std里会有一些template,所以在定义的时候,函数名字要注意,否者就会出现 C2668 的编译错误。
解决办法:
(1)改自定义的函数名称
(2)不使用using namespace std;
( 3 ) ::swap //means just use this file’ swap() function

类声明

template <class T>
your_func(T &x,T &y)
{
    T a;
    a=x;
    x=y;
    y=a;
}

上述就相当于是一件swap() 函数。

int main()
{
    swap(int, int)       //okay
    swap(double,double)  //okay
    swap(int,double)     //error
    return 0;
}

如果参数并没有在函数声明里,可以采用显式调用

template <class T>
void func(void)
{
    ...
}
func<int>();        //type T is int
func<double>();     //type T is double

例如:

#include <iostream>
using namespace std;

template <class T>
void foo(void)
{
    cout << "hello" << endl;
    int a = 3;
    T b = a;
    cout << b << endl;
}

int main()
{
    foo<int>();     //type T is int
    return 0;
}

上面是一些函数模板,下面介绍一个类模板。

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

template <class T>
class Vector {
public:
    Vector(int);
    ~Vector();
    Vector(const Vector&);
    Vector& operator=(const Vector& rhs);
    T& operator[](int);
private:
    T* m_elements;
    int m_size;
};

template <class T>
Vector<T>::Vector(int size) :m_size(size) {
    m_elements = new T[m_size];
}

template <class T>
Vector<T>::~Vector(){
    delete[] m_elements;
    m_elements = NULL;
}

template<class T>
Vector<T>::Vector(const Vector &)
{
    cout << "this is copy construcor" << endl;
}

template <class T>
Vector<T>& Vector<T>::operator=(const Vector& rhs) {
    *this = rhs;
    return *this;
}
//注意,在vs2015中,如果用这个构造函数的默认的定义,则会出现error:c2955。
//所以最好在每一个类的函数定义都通过explicit的方式定义函数,即Vector<T>


template <class T>
T& Vector<T>::operator[](int index) {
    if (index>0 && index<m_size) {
        return m_elements[index];
    }
    else {
        cout << "index is invalid" << endl;
    }
}

int main()
{
    Vector<int> v1(6);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值