【问题标题】:Having Problem for Object Initialization by Constructor in C++ [closed]C++ 中构造函数的对象初始化问题[关闭]
【发布时间】: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


【解决方案1】:

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

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

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

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

4-我添加了一个操作符来更容易地打印出属性。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    相关资源
    最近更新 更多