C++中构造函数的对象初始化出现问题

Having Problem for Object Initialization by Constructor in C++

本文关键字:问题 初始化 对象 构造函数 C++      更新时间:2023-10-16

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

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

我试图通过将对象分配给来初始化对象,使它们为空,给它们零和随机值,但它们没有工作。

学生.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

学生.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;
}

主.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-我添加了一个操作器,以便更轻松地打印出属性。

针对问题中的代码更新了所有更改