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

时间:2016-01-12 09:13:00

标签: c++ pointers inheritance multiple-inheritance nested-class

我试图使用嵌套类而不是多重继承。我按照本书的建议,但我在构造函数中不断收到错误。基本上,人是祖父,学生和员工是父母,助教是孩子。 TeachingAssistant将有一个嵌套类,它将引用它的外部类,但当我使用本书中的代码时,我得到两个错误

我收到错误

错误1 *“没有用于TeachingAssistant :: EmployeePart初始化的匹配构造函数”

和此错误

错误2 “'EmployeePart'的行外定义与'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) {}

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

2 个答案:

答案 0 :(得分:1)

您的基本问题是您错误地调用了EmployeePart构造函数,并错误地定义了它。但是,在我们修复它的同时,我们还将解决这样一个事实:您不应该使用new,而不是使用拥有内存的原始指针,而不是在不需要可空性时使用指针。 reseatability。

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) {}

答案 1 :(得分:0)

EmployeePart(TeachingAssistant&);

您的构造函数需要引用,但您正在使用is指针传递this employee_ptr = new EmployeePart(this);传递*而不是

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