C ++构造函数/类问题:错误 - 左边必须有类/ struct / union [英] C++ Constructor / Class Question: Error - left of must have class/struct/union

查看:553
本文介绍了C ++构造函数/类问题:错误 - 左边必须有类/ 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:

源文件:

#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;
    }
}

头文件:

#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;
}



我在一段时间没有做C ++,所以我确定它的东西真的很简单,但为什么空括号不工作? btw它也不工作,如果我只有一个没有参数的构造函数,或一个构造函数与默认参数。

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.

推荐答案

NumberGame newNumberGame();

声明一个函数 newNumberGame()参数并返回 NumberGame

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

C ++的语法生长了几十年,而不是被设计在一个单一的创作中。因此,它有许多模糊之处需要解决。这个歧义被解决为 a b()是一个函数声明,而不是一个对象定义。

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 a b() to be a function declaration rather than an object definition.

这篇关于C ++构造函数/类问题:错误 - 左边必须有类/ struct / union的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆