为什么我得到“预期”;错误和“范围内未声明的变量”错误?

时间:2010-09-18 20:57:02

标签: c++

我有以下代码

#include <iostream>
#include <set>
#include <string>
using namespace std;

template<class  Container>
void print(const Container &c)
{

   Container::const_iterator itr;
   for (itr=c.begin();itr!=c.end();itr++){
      cout<<*itr<< '\n';
}

}

int main(){

   set<string,greater<string>>s;
   s.insert("georgia");
   s.insert("saqartvelo");
   print(s);
   return 0;

}

但错误

reverse.cpp: In function ‘void print(const Container&)’:
reverse.cpp:9: error: expected ‘;’ before ‘itr’
reverse.cpp:10: error: ‘itr’ was not declared in this scope
reverse.cpp: In function ‘int main()’:
reverse.cpp:17: error: ‘s’ was not declared in this scope
reverse.cpp:17: error: ‘>>’ should be ‘> >’ within a nested template argument list

可能导致此问题的原因以及如何解决?

2 个答案:

答案 0 :(得分:7)

您需要typename Container::const_iterator而不是Container::const_iterator

在编译器正在读取代码时,它不知道Container具有这样的类型(它是所谓的依赖名称)。

答案 1 :(得分:5)

Alexandre对前两个错误是正确的。最后两个是由于C ++的一个恼人的语法限制:你需要在模板表达式的两个右括号之间有一个空格:

set<string,greater<string> > s;

否则,C ++会将其解释为右移>>运算符。