【问题标题】:How to write a constructor for a class who includes another class?如何为包含另一个类的类编写构造函数?
【发布时间】: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


【解决方案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 = "")

【讨论】:

  • 先谢谢!但是由于第三个原因它仍然无法正确编译
  • 所以我的主要功能可能有问题?我将更新代码并展示我的主要功能,请再次查看。
【解决方案2】:

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

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 = "")

【讨论】:

  • 谢谢!但是由于第三个原因它仍然无法正确编译 T^T
  • 你不能做Student s2;因为一旦您定义了自己的构造函数,默认构造函数就不再存在了。因此,学生 s2(e, f);至少。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多