【发布时间】:2019-08-11 20:55:54
【问题描述】:
我想在 C++ 中创建一个 Student 对象,它具有 name、major、age 和 id 属性。对象初始化将在 main() 部分完成,Student 对象具有所有构造函数的 get 和 set 方法。我想在 main() 部分打印学生对象,但出现此错误: 在 C++98 中,'s1' 必须由构造函数初始化,而不是由 '{...}'
我在代码块中使用 GNU GCC 编译器。我还没有专门编写任何用于编译或调试的代码。
我尝试通过将对象分配给 this 来初始化它们,使它们为空,给它们零和随机值,但它们没有工作。
Student.h 文件
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
string name, major;
int age, id;
Student(string name, string major, int age, int id);
string getName();
void setName(string name);
string getMajor();
void setMajor(string major);
int getAge();
void setAge(int age);
int getId();
void setId(int id);
};
ostream & operator << (ostream &out, Student &s);
#endif // STUDENT_H
Student.cpp 文件
#include "Student.h"
#include <iostream>
using namespace std;
Student::Student(string newName, string newMajor, int newAge, int newId)
{
name = newName;
major = newMajor;
age = newAge;
id = newId;
}
string Student::getName(){
return name;
}
void Student::setName(string newName){
name = newName;
}
string Student::getMajor(){
return major;
}
void Student::setMajor(string newMajor){
major = newMajor;
}
int Student::getAge(){
return age;
}
void Student::setAge(int newAge){
age = newAge;
}
int Student::getId(){
return id;
}
void Student::setId(int newId){
id = newId;
}
ostream & operator << (ostream &out, Student &s)
{
out << "Name: " << s.getName() << " Major: " << s.getMajor() << " Age: " << s.getAge() << " Id:" << s.getId() << endl;
return out;
}
Main.cpp 文件
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main()
{
Student s1 {"John","MATH",24,123456};
Student s2 {"Steve","ENG",22,654321};
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
我希望将学生的属性打印为列表,但是当我运行它时,程序崩溃并出现以下错误: ** 在 C++98 中,'s1' 必须由构造函数初始化,而不是由 '{...}' **
【问题讨论】:
-
你用的是什么编译器?必须告诉编译器要编译的 C++ 版本是什么?你用来编译的命令行是什么?您正在针对 C++98 进行编译并尝试使用 C++11 语法。
-
我在代码块中使用 GNU GCC 编译器。我还没有专门编写任何用于编译或调试的代码
-
请将此信息添加到您的问题中。 CodeBlocks 中有一个选项可以设置要编译的语言标准的版本它应该有一个下拉菜单,如下所示:C++11、C++14、C++17。选择一个并重新编译。 (我目前没有安装 CodeBocks,所以我对下拉菜单的内容并不准确)。
-
你的构造函数不使用它的参数,你的setter不更新任何值...?
标签: c++ class object initialization