[英]Passing an class type as a constructor argument C++
I am trying to learn c++ when I stumbled on a error.当我偶然发现一个错误时,我正在尝试学习 c++。 I have this class that inherits from the class PERSON.我有这个继承自 class PERSON 的 class。
#include <iostream>
#include <string>
class PERSON
{
private:
std::string name;
bool sex;
public:
PERSON(std::string name, bool sex) : name(name) , sex(sex){};
//methods
};
class TEACHER: public PERSON
{
private:
std::string title;
public:
TEACHER(std::string name, bool sex, std::string title) : PERSON(name,sex), title(title){};
//methods
};
Now the problem starts when I need to place this class TEACHER inside a constructor to create a class CLASSROOM, to pass them as arguments.现在问题开始了,当我需要将此 class TEACHER 放在构造函数中以创建 class CLASSROOM 时,将它们作为 arguments 传递。
class CLASSROOM : public TEACHER
{
private:
std::string name;
TEACHER lecturer;
TEACHER s_teacher;
public:
CLASSROOM(std::string name, TEACHER lecturer , TEACHER s_teacher){};
//methods
};
When I compile this its shows an "error no matching function for call to 'TEACHER::TEACHER()'" and I don't know how to initialize the CLASSROOM constructor.当我编译它时,它显示“错误没有匹配 function 以调用 'TEACHER::TEACHER()'”并且我不知道如何初始化 CLASSROOM 构造函数。 I tried few things like initializing the constructor as I would with the other constructors but the same error shows up.我尝试了一些事情,比如初始化构造函数,就像我使用其他构造函数一样,但出现了同样的错误。
A CLASSROOM is not a kind of TEACHER so I think don't really want to derive CLASSROOM
class from TEACHER
class. CLASSROOM 不是一种 TEACHER,所以我认为真的不想从TEACHER
class 派生CLASSROOM
class。
Once the above is corrected, you can then write the constructor as follows:一旦上述更正,您可以编写构造函数,如下所示:
class CLASSROOM
{
private:
std::string name;
TEACHER lecturer;
TEACHER s_teacher;
public:
CLASSROOM(std::string name, TEACHER lecturer , TEACHER s_teacher):
name(name),
lecturer(lecturer),
s_teacher(s_teacher) {};
//methods
};
You problem is here:你的问题在这里:
class CLASSROOM: public TEACHER
You told the compiler that your CLASSROOM is a TEACHER, and the error message just means that you have no so-called "default constructor" for a TEACHER (only one that takes name, sex, and title as arguments).您告诉编译器您的 CLASSROOM是TEACHER,错误消息仅表示您没有 TEACHER 的所谓“默认构造函数”(只有一个以姓名、性别和标题作为参数的构造函数)。
Of course, almost certainly, you don't want CLASSROOM to inherit from TEACHER.当然,几乎可以肯定,您不希望 CLASSROOM 继承自 TEACHER。 A classroom may have one or more teachers inside it, but it is not a teacher.一个教室里可能有一个或多个老师,但它不是老师。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.