#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的operator<<)。但我不知道如何定义专门类的模板友元函数。
此外,上面的代码显示了以下编译错误消息;
error C2248: 'test::y' : cannot access private member declared in class 'test'
附加问题:
Aaron McDaid 对我来说很好用,但我正在尝试重载ofstream类的operator<<。
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;
}
我使用了上面的代码。但似乎我不能使用os << t.y(它是int)。我不明白为什么会出现这种情况。错误信息如下:
error C2027: use of undefined type 'std::basic_ofstream<_Elem,_Traits>'
friend int a<>(int& x);
。 - Xeotest<int>
,而不是int
。 - Aaron McDaidtest
以两种不同的类型被实例化,那么Bo的答案也是错误的,因为它会产生ODR冲突。 - Xeofriend
行都应该替换为你的template<class U> friend int a(U& x);
?这样正确吗?我没有对你的回答进行投票,但我还没有准备好百分之百地点赞 :-) - Aaron McDaid