gpt4 book ai didi

c++ - 专门模板类的 friend (C++)

转载 作者:太空狗 更新时间:2023-10-29 20:29:58 25 4
gpt4 key购买 nike

#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 的运算符<<)。但是我不知道如何定义专门类的模板友元函数。

此外,上面的代码显示了这个编译错误信息;

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 不是模板,而是一个普通的函数:

friend int a(T& x); 

要拥有一个也是 friend 的模板,请尝试:

template<class U>
friend int a(U& x);

在评论中的讨论之后,也许我应该表明我打算将这些声明用于 test 类及其特化:

template <typename T>
class test
{
T y;

public:
test(T k) : y(k) {}

template<class U>
friend int a(U& x);
};

template <>
class test<int>
{
int y;
public:
test(int k) : y(k) {}

template<class U>
friend int a(U& x);
};

一个小缺点是这使得所有 a 函数成为所有 test 类的 friend ,但这通常不是什么大问题。

关于c++ - 专门模板类的 friend (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8533728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com