C++ 错误:预期的非限定 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10135244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:39:29  来源:igfitidea点击:

C++ error: expected unqualified-id

c++

提问by Seb

I'm getting an error "error: expected unqualified-id before '{' token" on line 6.

我在第 6 行收到错误“错误:在 '{' 标记之前预期为非限定 ID”。

I can't tell what's wrong.

我说不出怎么回事。

#include <iostream>

using namespace std;

class WordGame;
{
public:

    void setWord( string word )
    {
        theWord = word;
    }
    string getWord()
    {
        return theWord;
    }
    void displayWord()
    {
        cout << "Your word is " << getWord() << endl;
    }
private:
    string theWord;
}


int main()
{
    string aWord;
    WordGame theGame;
    cin >> aWord;
    theGame.setWord(aWord);
    theGame.displaymessage();

}

采纳答案by Alex Z

There should be no semicolon here:

这里不应该有分号:

class WordGame;

...but there should be one at the end of your class definition:

...但是在类定义的末尾应该有一个:

...
private:
    string theWord;
}; // <-- Semicolon should be at the end of your class definition

回答by keelerjr12

As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.

作为旁注,请考虑将 setWord() 中的字符串作为常量引用传递以避免过度复制。此外,在 displayWord 中,考虑将其设为 const 函数以遵循常量正确性。

void setWord(const std::string& word) {
  theWord = word;
}

回答by Beta

Get rid of the semicolon after WordGame.

去掉后面的分号WordGame

You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

你真的应该在班级小得多的时候发现这个问题。在编写代码时,每次添加六行代码时都应该进行编译。

回答by VJVJ

Semicolon should be at the end of the class definition rather than after the name:

分号应该在类定义的末尾而不是名称之后:

class WordGame
{
};

回答by Michael Alan Huff

For what it's worth, I had the same problem but it wasn't because of an extrasemicolon, it was because I'd forgotten a semicolon on the previous statement.

无论如何,我遇到了同样的问题,但这不是因为额外的分号,而是因为我忘记了前一条语句中的分号。

My situation was something like

我的情况是这样的

mynamespace::MyObject otherObject

for (const auto& element: otherObject.myVector) {
  // execute arbitrary code on element
  //...
  //...
} 

From this code, my compiler kept telling me:

从这段代码中,我的编译器不断告诉我:

error: expected unqualified-id before for (const auto& element: otherObject.myVector) { etc... which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ;after declaring otherObject.

error: expected unqualified-id before for (const auto& element: otherObject.myVector) { etc... 我认为这意味着我写错了 for 循环。不!我只是;在声明之后忘记了 a otherObject