2017-08-04 71 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) –

相关问题