C++ 错误:预期的不合格 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15437692/
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 19:21:36  来源:igfitidea点击:

error: expected unqualified-id

c++

提问by Johan Bj?reholt

So, i have searched around for answers, and multiple people have got the same error response but i cannot see how their errors could fix my code.

所以,我四处寻找答案,很多人都得到了相同的错误响应,但我看不出他们的错误如何修复我的代码。

I started trying out c++ yesterday, but i am experienced with mostly Python but also C#

我昨天开始尝试 C++,但我对 Python 和 C# 都有经验

I am making a simple contact book, just for learning. I am not done with the class or any other implementation, just need this fixed first.

我正在制作一本简单的通讯录,仅供学习。我没有完成类或任何其他实现,只需要先修复这个。

the exact error is

确切的错误是

kontaktbok.cpp:9: error: expected unqualified-id before 'public'

And the code is here

代码在这里

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

bool running = true;

public class Contact
{
    private:
        string firstname   = "";
        string lastname    = "";
        string phonenumber = "";

    public:
        Contact()
        {
            this.firstname = "Alfred";
        }
};

int main()
{
        cout << "Welcome to the Contact book!" << endl <<
                "Made by X";
    while (running)
    {
        cout << "1. Add contact"    << endl
             << "2. List contacts"  << endl
             << "3. Quit"           << endl;
        cout << "Choice: ";
        string mystr;
        getline(cin, mystr);
        int choice;
        stringstream(mystr) >> choice;
        switch (choice)
        {
            case 1: cout << "asd";
            case 2: cout << "asd2";
            case 3: running = false;
            default : cout << "Invalid integer";
        }
    }
    return 0;
}

Thanks in advance!

提前致谢!

回答by Luchian Grigore

public class Contactis not valid C++, use class Contactinstead.

public class Contact不是有效的 C++,请class Contact改用。

回答by Shafik Yaghmour

These changes will fix your issue, public Classis not valid C++, it should be just class:

这些更改将解决您的问题,public Class不是有效的 C++,它应该只是class

class Contact
{
  private:
      string firstname ;
      string lastname  ;
      string phonenumber ;

  public:
    Contact()
    {
        this->firstname = "Alfred";
    }

  };

Also, you should be using ->when dereferencing thisit is a pointer not a plain structor classin which using .would be valid. Also, member variables should be initialized in the constructor, if you want empty strings the default constructor constructs a empty string.

此外,->当取消引用this它是一个指针而不是普通指针structclass使用.将有效时,您应该使用。此外,成员变量应该在构造函数中初始化,如果你想要 empty strings 默认构造函数构造一个空 string