gpt4 book ai didi

c++ - STL 的依赖范围错误

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

#include <iostream>
#include <map>
#include <string>

using namespace std;

template <class T>
class Counter
{
public:
Counter()
{
totalCount
}

~Counter()
{
}

bool containsKey(T key)
{
map<T, double>::iterator it = counter.find(T);
if (it == counter.end()) return false;
return true;
}

private:
map<T, double> counter;
double totalCount;
};

int main()
{
Counter<string> table;
return 0;
}

此代码甚至无法编译,我无法弄清楚错误是什么。任何帮助,将不胜感激。谢谢!

编译命令

g++ counter.cpp

错误是

error: need ‘typename’ before ‘std::map<T, double>::iterator’ because ‘std::map<T, double>’ is a dependent scope

最佳答案

编译器从您的模板声明中知道 T 是一个类型的名称 (typename),但它不知道 std::map::iterator 是一个类型还是其他类型。因此,正如编译器所说,您必须在此语句之前添加“typename”,以告诉编译器它是一个类型的名称。

总结:改变

map<T, double>::iterator it = counter.find(T);

typename map<T, double>::iterator it = counter.find(T);

关于c++ - STL 的依赖范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17223446/

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