我写了一个“Student”类,它有两个名为“Course”和“Score”的类作为它的成员。
现在我编写了一个用于初始化“Student”类的构造函数并得到了这些错误:
1.缺少参数“e”的默认参数
2.“Student”的初始化没有匹配的构造函数
3.候选构造函数(隐式复制构造函数)不可行:需要 1 个参数,但为 Student 类提供了 0 个
更新:改类后,发现问题出在我的main函数上,请问如何解决?图片中的错误和警告我给出。
#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;
}
最佳答案
具有默认值的参数应始终放在参数列表的末尾。
因此,
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 = "")
关于c++ - 如何为包含另一个类的类编写构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55589875/