expected unqualified-id before 'for'

时间:2017-08-04 13:07:34

标签: c++

I have this code (I put just a part of it):

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

And I get this error:

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

I checked that all the brackets are correctly closed before and after the for loop.

What did I do wrong? Thank you!

1 个答案:

答案 0 :(得分: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;
}