簡體   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