Question

I've decided to take up C++ after nearly a decade of not messing with it, and I'm having an issue with some code, and having some great difficulty understanding what's wrong. I've seen several questions that are related, expected a class or namespace and Expected a class or namespace; syntax is proper and correct. as well as spending hours trying to research other ones, and i still can't figure this out.

mainwindow.hpp

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    std::vector<Card> cards;

    // Events:
public slots:
    void shuffle();

private:
    Ui::MainWindow *ui;
};

mainwindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {

    ...

    // Spades
    cards.push_back(Card(Suit::SPADES, Value::ACE)); // <- getting the errors here
    cards.push_back(Card(Suit::SPADES, Value::TWO)); // <-
}

the Card class just has a ctor with Suit suit, Value value which comes from another file.

I'm having difficulty understanding why i'm getting this error:

expected a class or namespace
   cards.push_back(Card(Suit::SPADES, Value::ACE));
                ^
Was it helpful?

Solution

I think I've figured out what you're doing wrong :)

What you were supposed to post is exactly the code below, less the correct section. That's all that we need to see to diagnose the issue. Your issue has nothing to do with Qt, etc. Really: minimization is the key. It saves everyone's time. Yours and ours.

#include <vector>

enum Suit { SPADES };
enum Value { ACE, TWO };

class Card {
public:
   Card(Suit, Value) {}
};

int main()
{
   std::vector<Card> cards;
   // Correct
   cards.push_back(Card(SPADES, ACE));
   cards.push_back(Card(SPADES, TWO));
   // Wrong since Suit and Value are not classes nor namespaces,
   // they are merely enum tags.
   cards.push_back(Card(Suit::SPADES, Value::ACE));
   cards.push_back(Card(Suit::SPADES, Value::TWO));
   return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top