如何为包含另一个类的类编写构造函数?

时间:2019-04-09 09:48:36

标签: c++ class constructor

我写了一个'学生'类,它有两个叫做'Course'和'Score'的类作为其成员。
现在,我为“学生”类的初始化编写了一个构造函数,并得到以下错误:
1. 缺少参数'e'的默认参数
2. 没有用于初始化“学生”的匹配构造函数
3. 候选构造函数(隐式副本构造函数)不可行:需要1个参数,但为Student类提供了0个

更新:更改类后,现在我发现问题出在我的主函数中,该如何解决?我在图片中给出了错误和警告。

#include <iostream>
#include <string>
using namespace std;
class Course
{
    friend void readCourse(Course &scourse);
public:
    Course(Course &scourse) : cno(scourse.cno), cname(scourse.cname) { }
    Course(const string &a, const string &b) : cno(a), cname(b) { }
    void course_show();
private:
    string cno;
    string cname;
};
class Score
{
    friend void readScore(Score &sscore);
public:
    Score(Score &sscore) : score(sscore.score) { }
    Score(int a) : score(a) { }                                                                                                                                                                                          
    void score_show();
private:
    int score;
};
class Student
{
    friend void readStudent(Student &student);
public:
    Student(const string a = "", const string b = "", const string c = "", const string d = "",
        Course e, Score f) : sno(a), sname(b), gender(c), grade(d),
            scourse(e), sscore(f) { }
    void student_show();
private:
    string sno;
    string sname;
    string gender;
    string grade;
    Course scourse;
    Score sscore;
};

int main()
{
    Student s1;
    Student s2;
    readStudent(s1);
    readStudent(s2);
    s1.student_show();
    s2.student_show();
    return 0;
}

errors and warnings

2 个答案:

答案 0 :(得分:3)

带有默认值的参数应始终放在参数列表的末尾。

因此

Student(const string a = "", const string b = "", const string c = "", const string d = "",
        Course e, Score f)

应该是

Student(Course e, Score f, const string a = "", const string b = "", const string c = "", const string d = "")

答案 1 :(得分:1)

默认参数应移至参数列表的末尾。

Student(const string a = "", const string b = "", const string c = "", const string d = "", Course e, Score f)

以上内容必须更正为

Student(Course e, Score f, const string a = "", const string b = "", const string c = "", const string d = "")
相关问题