【发布时间】:2019-04-09 09:48:35
【问题描述】:
我编写了一个“学生”类,它有两个类,分别称为“课程”和“分数”。
现在我为“Student”类的初始化编写了一个构造函数并得到了这些错误:
1.参数“e”缺少默认参数
2.'Student'的初始化没有匹配的构造函数
3.候选构造函数(隐式复制构造函数)不可行:需要 1 个参数,但为学生类提供了 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;
}
【问题讨论】:
-
将您的错误/警告粘贴为纯文本,而不是图像形式。
-
您不需要定义仅按成员复制的复制构造函数,这样做会抑制您原本会得到的隐式移动构造函数。
-
字符串的默认值不需要设置为""。由于您始终可以添加多个 c'tors 作为 Student(Cource a, Score b) 等等...
标签: c++ class constructor