使用Diamond of death进行C ++打印

时间:2018-06-13 19:46:20

标签: c++ oop polymorphism diamond-problem

首先让我解释一下我的层次结构:

        Person
       /     \
   Student Employee
       \     /
       Intern

每个类都有自己的output函数,用于打印其数据成员,我只需要打印Person一次。问题是StudentEmployee不是抽象类,人们也会创建一个类型的对象,所以我不仅可以调用Intern级别的输出函数。

正如您将在下面的代码中看到的那样,我已经设法解决了这个问题,但我认为这很丑陋并且不是非常多态的。我已经创建了一个额外的输出函数,因此它适用于所有情况。有没有更好的方法来实现这一目标?

class Person {
    string name;
    int id;
public:
        virtual void output(ostream& out) {
        out << name << "," << id;
    }
}

学生:

class Student : virtual public Person {
    string major;
    int year;
public:
    virtual void output(ostream& out) {
        Person::output(out);
        out << "," << major << "," << year;
    }
    virtual void outputStudOnly(ostream& out) {
        out << "," << major << "," << year;
    }
};

员工:

class Employee : virtual public Person{
    string jobTitle;
public:
    virtual void output(ostream& out) {
        Person::output(out);
        out << "," << jobTitle;
    }
    virtual void outputEmpOnly(ostream& out) {
        out << "," << jobTitle;
    }
};

实习生:

class Intern : public Student, public Employee {
public:
    virtual void output(ostream& out) {
        Person::output(out);
        Student::outputStudOnly(out);
        Employee::outputEmpOnly(out);
    }
};

1 个答案:

答案 0 :(得分:2)

那是什么模板方法。以下是我编写此代码的方法:

class Person {
    string name;
    int id;
public:
        void output(ostream& out) {
        out << name << "," << id;
        output_impl(out);
    }
private:
       virtual void output_impl(ostream& ) {}
};

class Student : virtual public Person {
    string major;
    int year;
private:
    virtual void output_impl(ostream& out) {
        out << "," << major << "," << year;
    }

};

class Employee : virtual public Person {
    string jobTitle;
private:
    virtual void output_impl(ostream& out) {
        out << "," << jobTitle;
    }
};

class Intern : public Student, public Employee {
private:
    virtual void output_impl(ostream& out) {
        Student::output_impl(out);
        Employee::output_impl(out);
    }
};

而不是在对象上调用output