简体   繁体   中英

C++ Constructor / Class Question: Error - left of must have class/struct/union

I realise what this error means, the thing that is puzzling me is why I get it. I have emulated the error in this tiny program for the sake of this question. Here is the code:

source file:

#include "RandomGame.h"

using namespace std;

NumberGame::NumberGame(int i)
{
    upperBound = i;

    numberChosen = 1 + rand() % upperBound;
}

NumberGame::NumberGame()
{
    upperBound = 1000;

    numberChosen = 1 + rand() % upperBound;
}

int NumberGame::guessedNumber(int g)
{
    if (g == numberChosen)
    {
        return 2;
    }
    else if (g < numberChosen)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

header file:

#ifndef NUMBERGAME_H
#define NUMBERGAME_H
#include <iostream>
using namespace std;

class NumberGame
{
private:
    int upperBound;
    int numberChosen;
    int g;
public:
    NumberGame(int);

    NumberGame();

    int guessedNumber(int);
};

#endif

main:

#include <iostream>
#include <cstdlib>
#include "RandomGame.h"
using namespace std;

int makeEven(int);

int main()
{
    //only one of these lines will remain uncommented
    NumberGame newNumberGame(5); // works
    NumberGame newNumberGame;    // works
    NumberGame newNumberGame();  // doesn't work


     // I get the error here, apparently when using empty brackets, newNumberGame 
     //is not a class anymore. wwwhhyyyyy??????
    newNumberGame.guessedNumber(5);

    return 0;
}

I haven't done C++ in a while so i'm sure it's something really simple, but why doesn't the empty brackets work? btw it also doesn't work if I just have one constructor with no arguments, or one constructor with a default argument.

This

NumberGame newNumberGame();

declares a function newNumberGame() taking no arguments and returning a NumberGame .

C++'s grammar is grown over several decades, rather than being designed in a single act of creation. Consequently, it has many ambiguities that needed to be resolved. This ambiguity was resolved for ab() to be a function declaration rather than an object definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM