gpt4 book ai didi

c++ - 错误 : 'e' is not a class, 命名空间或枚举

转载 作者:行者123 更新时间:2023-11-30 01:42:18 24 4
gpt4 key购买 nike

我正在尝试重载运算符 << 以仅打印 STL 容器的每两个元素。但是我在编译过程中出现错误:

error: 'e' is not a class, namespace, or enumeration

这是我的代码:

#include <iostream>
#include <vector>

template<typename T>
std::ostream& operator<<(std::ostream &out, T const &e){
for(e::iterator it = e.begin(); it != e.end(); it = it + 2){
out << *it << " ";
}
return out;
}

int main(){
std::vector<int> v;
for(int i= 0; i < 10; i++){
v.push_back(i);
}

std::cout << v;
return 0;
}

最佳答案

这里有两个问题。

一个是 e::iterator。您不能通过对象访问成员类型,您需要使用该类型。相反,您应该只使用 auto it = e.begin()。如果你不能使用 C++11,那么你需要使用

typename T::const_iterator it = e.begin()

typename 是必需的,因为名称依赖于模板参数,const_iterator 是必需的,而不仅仅是 iterator,因为参数标记为 const

但是,您更严重的错误是首先使此过载。

template<typename T>
std::ostream& operator<<(std::ostream &out, T const &e){

这为任何类型std::ostream 输出声明了一个重载。这肯定会让你头疼,而且,果然,如果你修复了第一个错误,你在尝试输出 "":

时会得到一个模糊的函数调用错误:
main.cpp:7:20: error: use of overloaded operator '<<' is ambiguous (with operand types '__ostream_type' (aka 'basic_ostream<char, std::char_traits<char> >') and 'const char [2]')
out << *it << " ";
~~~~~~~~~~ ^ ~~~

如果你真的想让它与每个标准库容器一起工作,我猜你会检查是否存在类似 T::iterator 的东西,并且只有在存在时才启用你的重载。像这样:

template<typename T, typename = typename T::iterator>
std::ostream& operator<<(std::ostream &out, T const &e){
for(auto it = e.begin(); it != e.end(); it = it + 2){
out << *it << " ";
}
return out;
}

Live demo

关于c++ - 错误 : 'e' is not a class, 命名空间或枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39846874/

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