模版类的友元函数的问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 19:24:56
#include<iostream>
#include<string>
using namespace std;

template<class A>
void counts();

template<class T>
class app
{
private:
T item;
static int ct;
public:
app(int a=0):item(a){ct++;};
~app(){ct--;};
friend void counts();
};

template<class T>
int app<T>::ct=0;

template<class A>
void counts()
{
cout<<"ct:"<<app<A>::ct<<sizeof(app<A>)<<endl;
};

void main()
{app<double> a3(6);
app<int> a1(2);
app<int> a2(4);
counts<int>();
counts<double>();

};

这个是摸版类中的友元摸版函数
为什么答案是两个一样的
而不应该是 ct:24
ct:18
呢?
如果是我用错了请赐教~

在app类内部,声明 friend void counts();
时不对,应该是friend void counts <T>();
否则在调用这个函数时会认为调用的非模板函数。另外你这个程序是在VC6下面编译运行的吧,而且没报错,但是将你原来的程序放到gcc或者VS2005是有错的,改后在VC6中会报错,但是在GCC和VS2005下就对了。

VC6比较老了,估计对类的模板什么的支持不好,所以建议你换个新的编译环境试一下。