C++中的类模板应用问题

在C++中,类模板的使用有一些特殊的问题,大家都知道,C++中类的出现是为了实现封装,达到信息的隐藏,很多时候,类的声明和实现细节是分到不同的文件进行编写的,但是在模板中,因为一些特殊的原因(对模板参数无法分辨),必须要将两部分写道同一个文件中,并且,因为模板的复杂性,其默写特殊形式的声明也比较特别。下例为网上摘录的一个片段(其中做了部分修改,另,因为记不得准确的出处,所以不知道该怎么声明,还请原作者见谅),

//#include <stdafx.h>

#include <iostream>
using namespace std;
#if 0
template <class T>
class Box;

template <class T>
Box<T> operator+ (const Box<T> &, const Box<T> &);

template <class T>
Box<T> operator+ (const Box<T> &, const T &);

template <class T>
Box<T> operator+ (const T &, const Box<T> &);

template <class T>
ostream& operator<< (ostream &, const Box<T> &);
#endif   // end #if 0

template <class T>
class Box{
public:
    Box();
    Box(const T &);
    void f();
    void f(T &);
    static void sta();
 template<class T>
    friend Box<T> operator+ (const Box<T> &, const Box<T> &);
 template<class T>
    friend Box<T> operator+ (const Box<T> &, const T &);
 template<class T>
    friend Box<T> operator+ (const T &, const Box<T> &);
 template<class T>
    friend ostream& operator<< (ostream &, const Box<T> &);

private:
    T tt;
};


#if 1

template <class T>
void Box<T>::sta(){
    T a = (T)100;
    cout << a << "This is a static function!" <<endl;
}

template <class T>
Box<T>::Box(){
    tt = 0;
}

template <class T>
Box<T>::Box(const T& newt){
    tt = newt;
}

template <class T>
void Box<T>::f(){
    T t = 100;
    tt = t;
    cout << tt << endl;
}

template <class T>
void Box<T>::f(T &a){
    T t = 100;
    tt = t;
    cout << tt << endl;
}

template <class T>
Box<T> operator + (const Box<T> &a, const T &b){   
    return Box<T>(a.tt + b);
}

template <class T>
Box<T> operator+ (const T &a, const Box<T> &b){
    return b+a;
}

template <class T>
Box<T> operator+ (const Box<T> &a, const Box<T> &b){
    return Box<T> (a.tt + b.tt);
}

template <class T>
ostream & operator << (ostream &os, const Box<T> &a){
    return os << a.tt << endl;
}
#endif   // end #if

对于这段代码,有如下几点需要注意:

第一,友元函数的声明形式。因为其形式同样为模板函数,也就是标准中的成员函数模板(可能有些编译器不支持这个特性),在声明的时候必须加上关键字template <class T>,如果不加上的话,在VC6.0中会提示你无法访问private变量,在vs2005中会提示链接错误,即使你将其中的private member data变成了public,在VC6.0中通过,也按你的预期执行了(虽然我认为其中还应该有些问题,甚至有可能是你声明的友元根本就没有当作友元,或者说你声明的友元并没有真正的实现,你真正实现的似乎是同名的函数是一个全局的函数,那么他就可以访问你的被改为public的数据成员,达到你想要的结果,但执行的不是你的友元函数,而是一个全局的函数模板),但是在VS2005中依然链接错误,所以,关键字template <class T>一定要加上--虽然有点麻烦:)

第二,关于类模板中构造函数。正确形式如下:

template <class T>
Box<T>::Box(){
    tt = 0;
}

写成如下的形式会发出一个警告,这可不是什么好兆头。它说明你为每一个实例化的类都编写了特定的构造函数,或者说,你写的构造函数只是为特定类实现的,你真的需要这么做么?

template <class T>
Box<T>::Box<T>(){
    tt = 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值