首页 文章

c上动态数组创建出错

提问于
浏览
-1

我的作业有问题 . 我写了一个Student类,它的构造函数只包含一个学生的id和名字 . 这是构造函数和get方法:(我不会把另一部分因为无关紧要)

#include <iostream>
#include "SimpleStudent.h"
using namespace std;

Student::Student(const int sid , const string sname ) {
    studentId = sid;
    studentName = sname;
}
string Student::getStudentName() {
    return studentName; 
} 

void Student::operator=(const Student &right) {
    if (&right != this) {
        if (studentId != right.studentId) {
            studentId = right.studentId;
        }
        if (studentName != right.studentName) {
            studentName = right.studentName;
        }
    }
}

请注意,studentId和studentName分别在私有部分的标头中声明为int和string .

这是测试部分:

#include <iostream>
#include "SimpleSRS.h"
using namespace std;
int main() {
    Student* x = new Student[1];
    Student* s1 = new Student(1,"er");
    x[0] = *s1;    
    cout << x[0].getStudentName() << endl;
    return 0;
}

当我运行上面的代码时,我收到以下错误:

在抛出'std :: logic_error'basic_string :: _ S_construct null的实例后无效的终止调用

我无法弄清楚这个问题 . 谢谢

编辑:这是头文件:

#ifndef __SIMPLE_STUDENT_H
#define __SIMPLE_STUDENT_H
#include <string>
using namespace std;

class Student {
public:
    Student(const int sid = 0, const string sname = 0);
    Student();
    ~Student();
    Student(const Student &studentToCopy);
    void operator=(const Student &right);
    int getStudentId();
    string getStudentName();
private:
    int studentId;
    string studentName;
};
#endif

1 回答

  • 2

    你失败了,因为你将null传递给std :: string的构造函数 . 这是不允许的 . 你在这里做

    Student(const int sid = 0, const string sname = 0);
    

    它也不清楚为什么你有2个构造函数

    Student(const int sid = 0, const string sname = 0);
        Student();
    

    这些基本相同 .

    我会删除第一个 . 现在studentName将被默认构造(空)

相关问题