使用嵌套 类 而不是多重继承,C++

Using Nested Classes Instead of Multiple Inheritance, C++

我正在尝试使用嵌套 classes 而不是多重继承。我正在按照书中的建议进行操作,但构造函数中一直出现错误。基本上,Person 是祖父,Student 和 Employee 是 Parent,助教是 child。 TeachingAssistant 将有一个嵌套的 class,它将引用其外部 class,但是当我使用书中的代码时,我得到两个错误

我收到错误

错误 1 ​​"No matching constructor for Initialization of TeachingAssistant::EmployeePart"

和这个错误

错误 2 "Out of line definition of 'EmployeePart' does not match any declaration in 'TeachingAssistant::EmployeePart'"

代码如下:

class TeachingAssistant : public Student
{
public:
    TeachingAssistant();
private:
    class EmployeePart;
    EmployeePart* employee_ptr;
};

class TeachingAssistant::EmployeePart : public Employee
{
public:
    EmployeePart(TeachingAssistant&);
private:
    TeachingAssistant* ta_part; // Allows access back to outer class
};

此构造函数中存在错误 1 ​​

TeachingAssistant::TeachingAssistant()
{
    employee_ptr = new EmployeePart(this); // Pass pointer to implicit parameter
}

出现错误 2

TeachingAssistant::EmployeePart::EmployeePart(TeachingAssistant* taval)
: ta_part(taval) {}

如果我提供构造函数,为什么会弹出这些错误?

EmployeePart(TeachingAssistant&);

您的构造函数需要引用,但您传递的 this 是指针 employee_ptr = new EmployeePart(this); 改为传递 *this

第二个错误。您的声明与定义不同。参见 TeachingAssistant* tavalEmployeePart(TeachingAssistant&);

您的基本问题是您错误地调用了 EmployeePart 构造函数,并且错误地定义了它。然而,在我们解决这个问题的同时,我们也会解决这样一个事实,即您应该更愿意不使用 new,不使用拥有内存的原始指针,并且在不需要可空性或不需要时不使用指针可重装性。

class TeachingAssistant : public Student
{
public:
    TeachingAssistant();
    TeachingAssistant(const TeachingAssistant&rhs) = delete;   // Delete copy constructor.
    TeachingAssistant& operator=(const TeachingAssistant&rhs) = delete; // And assignment.
private:
    class EmployeePart;
    std::unique_ptr<EmployeePart> employee_ptr;    // First change here.
};

class TeachingAssistant::EmployeePart : public Employee
{
public:
    EmployeePart(TeachingAssistant&);    
private:
                                // Second change here.  Store reference, not pointer.
    TeachingAssistant& ta_part; // Allows access back to outer class
};

在初始化列表中创建employee_ptr,并传递*this,而不是this

TeachingAssistant::TeachingAssistant()
  : employee_ptr(std::make_unique<EmployeePart>(*this))  // Pass reference to constructor
{
}

第四个变化在下一行:

TeachingAssistant::EmployeePart::EmployeePart(TeachingAssistant& taval)
: ta_part(taval) {}