重载<<时 模板类中私有成员无法直接访问而非模板类可以直接访问
这个是非模板类的实现,在VC6下编译通过
#include <iostream>
using namespace std;
class ZTest;
ostream& operator << ( ostream& os,const ZTest& test);
class ZTest
{
friend ostream& operator << ( ostream& os,const ZTest& test);
public:
ZTest ():a(0),b(0) {}
void set (int i,int j) { a=i;b=j; };
private:
int a;
int b;
};
ostream& operator << ( ostream& os, const ZTest& test )
{
os <<"("<< test.a << " " << test.b << ")";
return os;
}
int main ()
{
ZTest ti;
ti.set(9,10);
cout << ti << endl;
return 0;
}
这是模板类的实现,编译报错
error C2248: 'a' : cannot access private member declared in class 'ZTest<int>'
error C2248: 'b' : cannot access private member declared in class 'ZTest<int>'
test.exe - 2 error(s), 0 warning(s)
#include <iostream>
using namespace std;
template <class T> class ZTest;
template <class T> ostream& operator << ( ostream& os,const ZTest<T>& test);
template <class T>
class ZTest
{
friend ostream& operator << ( ostream& os,const ZTest<T>& test);
public:
ZTest ():a(0),b(0) {}
void set (T i,T j) { a=i;b=j; };
private:
T a;
T b;
};
template <class T> ostream& operator << ( ostream& os, const ZTest<T>& test )
{
os <<"("<< test.a << " " << test.b << ")";
return os;
}
int main ()
{
ZTest<int> ti;
ti.set(9,10);
cout << ti << endl;
return 0;
}