2017-08-04 73 views
-5

我有這樣的代碼(我把只是它的一部分):預期不合格-ID之前「爲」

class TMTrackAnalyzer : public edm::EDAnalyzer { 
    public: 
     # declare public stuff here 
    private: 
     # declare private stuff here 
     for(int i=1;i<=10;i++){ 
     cout<<i; 
     } 
    }; 

而且我得到這個錯誤:

expected unqualified-id before 'for' 
for(int i=1;i<=10;i++){ 

我檢查了所有括號在for循環前後正確關閉。

我做錯了什麼?謝謝!

+1

在類定義中不能有'for'循環。它屬於一個功能體。 –

+1

你不能只在這裏放置一個'for'循環。 – DimChtz

+0

你爲什麼不爲這個循環做一個方法? – retinotop

回答

0

閱讀C++類的基礎知識將大大受益。他們非常強大,但他們有需要遵循的規則。

退房這個帖子,看的頭文件是如何工作的,以及爲什麼我們使用它們:Header Files

TMTrackAnalyzer.h:

#include <string> 

class TMTrackAnalyzer : public edm::EDAnalyzer { 
public: 
    //declare public stuff here 
    TMTrackAnalyzer(int n) {num = n;} //constructor 
private: 
    string getPrintString(); 
    int num; //data member of TMTrackAnalyzer class 
    # declare private stuff here 

}; 

TMTrackAnalyzer.cpp:

#include "TMTrackAnalyzer.h" 

string TMTrackAnalyzer::getPrintString() 
{ 
    string temp = ""; 
    for(int i = 1; i <= num; i++){ 
     string = string + i + "\n"; 
    } 
    return string 
} 

Main.cpp:

#include "TMTrackAnalyzer.h" 
#include <iostream> 
using namespace std; //not ideal but works for the example 
int main() 
{ 
    TMTrackAnalyzer tm(10); //call constructor 
    cout << tm.getPrintString(); 
    return 0; 
} 
+0

謝謝你的想法。然而,在循環中,我想聲明一些類成員(cout <<僅僅是一個例子)。那麼在這種情況下,我還可以做你建議的嗎?如果沒有那些私人成員,那麼tm對象會不會被初始化,我也需要在其他函數中調用它? – BillKet

+0

在cpp中使用命名空間有什麼問題? – Eddge

+1

@Eddge在常規的'.cpp'中使用它並沒有什麼問題,但main不僅僅是一個常規的'.cpp'。我最近剛剛瞭解到[在這個問題上](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) –

相關問題