在 C++ 中通过构造函数初始化对象时遇到问题

Having Problem for Object Initialization by Constructor in C++

我想用C++创建一个Student对象,它有name、major、age和id的属性。对象初始化将在 main() 部分完成,Student 对象具有所有构造函数的 get 和 set 方法。我想在 main() 部分打印学生对象,但出现此错误: 在 C++98 中 's1' 必须由构造函数初始化,而不是由 '{...}'

我在 Codeblocks 中使用 GNU GCC Complier。我没有专门编写任何用于编译或调试的代码。

我试图通过将对象分配给 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' 必须由构造函数初始化,而不是由 '{...}' **

我解决了我的问题。有一些问题所以在这里我将详细解释我的解决方案。

1-我的代码是用 C++11 语法编写的,但我使用的是 C++98 语法,所以我将编译器更改为 C++11。

2-我的初始化错误,我使用了newName,newAge...等新变量来改变Student对象的属性。

3-我的设置方法是错误的,所以我改变了它们类似于我的初始化。

4-我添加了一个运算符来更轻松地打印出属性。

问题中代码的所有更改都已更新