#include <iostream>
using namespace std;
template <typename T>
class test
{
T y;
public:
test(T k) : y(k) {}
friend int a(T& x);
};
template <typename T>
int a(T& x)
{
cout << x.y;
return 9;
}
template <>
class test<int>
{
int y;
public:
test(int k) : y(k) {}
friend int a(int& x);
};
template <>
int a<int>(int& x)
{
cout << "4";
return 0;
}
int main(int argc, char* argv[])
{
test<int> z(3);
a(z);
return 0;
}
我想交个朋友类测试类的(在真实情况下,这是一个运营商的ofstream的< <)。但我不知道如何定义专业类的模板好友功能。朋友专门的模板类(C++)
此外,上面的代码显示了这个编译错误信息;
错误C2248: '测试:: Y':不能访问私有成员在 类 '测试'
问题补充申报;
亚伦麦克戴德适合我,但我试图超载运营商< < ofstream class。
friend ofstream& operator<< <test<int>> (ofstream& os, const test<int>& t);
我添加到以上测试类和
template<>
ofstream& operator<< <test<int> > (ofstream& os, const test<int>& t)
{
os << t.y;
return os;
}
使用上面的代码的代码。但它看起来像我不能使用操作系统< < t.y(这是INT)我不明白为什么会发生这种情况。该错误消息是
错误C2027:使用未定义的类型 '的std :: basic_ofstream < _Elem,_Traits>'
或'朋友诠释一个<>(INT & x);` – Xeo 2011-12-16 11:54:37
@Xeo,这是不正确的参数是'测试``不int` –
2011-12-16 12:34:15
@Aaron:对,我没注意到。然而,Bo的回答也是错误的,因为如果`test`被实例化为两种不同的类型,它会产生ODR违规。 – Xeo 2011-12-16 12:38:16