user2454455
user2454455

Reputation:

Syntax error on class definition

Eclipse says : a function definition is not allowed before token '{' (at lines of the implementation)

What am I missing?

#include <iostream>
using namespace std;

int main(){

    class MainButton {
        int a;
    public:
        void pressed();
        void released();
    };

    void MainButton::pressed() {
        cout<<"Button pressed";
    }

    void MainButton::released(){
        cout<<"Button released";
    }

    return 0;
}

Upvotes: 0

Views: 268

Answers (3)

zumalifeguard
zumalifeguard

Reputation: 9016

You cannot define the methods in that way.

The only way you can define the pressed() and released() methods inside the main() function is to define the methods inline to the class. Your other option is to move the entire definition of the class outside of the main function().

Upvotes: 0

PlasmaPower
PlasmaPower

Reputation: 1878

Your class definition & implementation should be outside the main method:

#include <iostream>
using namespace std;

class MainButton {
    int a;
public:
    void pressed();
    void released();
};

void MainButton::pressed() {
    cout<<"Button pressed";
}

void MainButton::released(){
    cout<<"Button released";
}

int main(){
    return 0;
}

This is because the class is not part of just the main method, but the whole program (other functions should be able to access it).

To use it, you could do:

int main(){
    MagicButton mb = new MagicButton();
    mb.pressed();
    return 0;
}

Upvotes: 0

Mert Akcakaya
Mert Akcakaya

Reputation: 3149

You are trying to define a class in a function, in this case int main(). You need to move your class definition out of the scope of this function.

Upvotes: 2

Related Questions