【问题标题】:Why do I get "Expected ;" error and "Variable not declared in scope" error?为什么我会得到“预期的;”错误和“变量未在范围内声明”错误?
【发布时间】:2011-04-14 04:40:49
【问题描述】:

我有以下代码

#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

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

【问题讨论】:

标签: c++


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    set<string,greater<string> > s;
    

    否则,C++ 将其解释为右移 &gt;&gt; 运算符。

    【讨论】:

    • 啊还有其他错误吗? ;) 我实际上并没有阅读依赖查找...
    猜你喜欢
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多