How to write a constructor for a class who includes another class?

Refresh

April 2019

Views

61 time

1

I write a 'Student' class which has two classes called 'Course' and 'Score' as its members.
Now I write a constructor for initialization of 'Student' class and get these errors:
1.missing default argument on parameter 'e'
2.no matching constructor for initialization of 'Student'
3.candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided for class Student

update: After change the class, now I find the problem is in my main function, how to solve this? I give the errors and warnings in the picture.

#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 answers

3

Parameters with default values should always be placed at the end of the parameter list.

Hence,

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

should be

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

Default parameters should be moved to the end of the argument list.

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

The above must be corrected as,

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