所以,我一直在寻找答案,多个人都有相同的错误响应,但我无法看到他们的错误如何修复我的代码.
我昨天开始尝试使用c ++,但我很熟悉Python,但也有C#
我正在制作一本简单的联系簿,仅供学习.我没有完成这个类或任何其他实现,只需先修复它.
确切的错误是
kontaktbok.cpp:9: error: expected unqualified-id before 'public'
Run Code Online (Sandbox Code Playgroud)
代码在这里
#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;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
这些更改将解决您的问题,public Class是无效的C++,应该只是class:
class Contact
{
private:
string firstname ;
string lastname ;
string phonenumber ;
public:
Contact()
{
this->firstname = "Alfred";
}
};
Run Code Online (Sandbox Code Playgroud)
此外,您应该->在解除引用时使用this它不是普通的指针struct或class使用.有效的指针.另外,成员变量应该在构造函数中初始化,如果你想要空,则string默认构造函数构造一个空字符串.