繁体   English   中英

为什么会出现“预期;”错误和“变量未在范围内声明”错误?

[英]Why do I get “Expected ;” error and “Variable not declared in scope” error?

我有以下代码

#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

是什么原因造成的,我该如何解决?

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

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

亚历山大对前两个错误是正确的。 最后两个是由于C ++令人讨厌的语法限制所致:您需要在模板表达式的两个右方括号之间留一个空格:

set<string,greater<string> > s;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM