gpt4 book ai didi

c++ - operator<< 不能使用其 friend 数组的 IT 成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:46:10 24 4
gpt4 key购买 nike

我想,如果我让 operator<< 成为他的 friend 数据结构(按名称排列);

//Forward Declarations
template<typename S, typename T>
struct array;

template<typename U, typename V>
ostream& operator<< (ostream& ous, const array<U, V>& t);

然后,我就可以做这样的事情了;在 operator <<

的实现中
//operator<< is a friend of struct array{} already
template<typename T, typename U>
ostream& operator<< (ostream& os, const array<T, U>& var){

if(var){
/*Error: 'IT' was not declared in this scope*/

for(IT it = var.data.begin(); it != var.data.end(); it++){
/*and i thought i need not redeclare IT before using it
since operator<< is a friend of array already*/
}
}
else{cout << "empty";}

return os;
}

现在,这是数组的实现:

/*explicit (full) specialization of array for <type, char>*/
template<>
template<typename Key>
struct array<Key, char>{

//data members
map<const Key, string> data;
typedef map<const Key, string>::iterator IT;

//member function
friend ostream& operator<< <>(ostream& ous, const array& t);

//other stuff/functions
};

最后,当我这样试驾时,编译器很生气;

void Test(){
array<int, char> out;
out[1] = "one"; //Never mind. this has been taken care of
out[2] = "two";
cout << out; //Error: 'IT' was not declared in this scope
}

问题:我究竟做错了什么,或者,为什么我不能直接访问和使用IT(数组中的 typedef),即使在我声明了运算符 <<(请求 IT)之后作为数组结构的 friend ?

最佳答案

for( typename array<T, U>::IT it = var.data.begin(); it != var.data.end(); it++){

并改变

typedef map<const Key, string>::iterator IT;

typedef typename std::map<const Key, string>::const_iterator IT;

这是一个演示程序,为了简单起见,我使用了 std::array 而不是 std::map。我认为它可以帮助你。

#include <iostream>
#include <array>

template <typename T, size_t N>
struct A
{
std::array<T, N> a;

typedef typename std::array<T, N>::const_iterator IT;
};

template <typename T, size_t N>
std::ostream & operator <<( std::ostream &os, const A<T, N> &a )
{
for ( typename A<T, N>::IT it = a.a.begin(); it != a.a.end(); ++it ) os << *it << ' ';

return os;
}

int main()
{
A<int, 10> a = { { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } };

std::cout << a << std::endl;

return 0;
}

程序输出为

0 1 2 3 4 5 6 7 8 9 

关于c++ - operator<< 不能使用其 friend 数组的 IT 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38011060/

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