是否有一个优雅的版本可以访问另一个子类的方法? 为了更好的理解,请观看我的c ++代码。
外部函数/类可以进一步访问addchild()方法非常重要!
C ++代码:
class User {
protected:
int userid;
std::string givenname;
std::string surname;
std::string birthday;
};
class Child: public User {
public:
int addchild() {
//Doing the required stuff to add a new child
}
};
class Parent: public User {
public:
int addparent() {
//Here we have to add a new child among others
addchild();
}
};
int main() {
Child child1;
child1.addchild();
Parent parent1;
parent1.addparent();
}
UML:
答案 0 :(得分:0)
您可以将CRTP用于您的父类:https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/(更一般的说法是:https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)
由于没有引起注意,我更改了原始代码示例,使其使用了CRTP:
#include <string>
class User {
protected:
int userid;
std::string givenname;
std::string surname;
std::string birthday;
};
class Child: public User {
public:
int addchild() {
//Doing the required stuff to add a new child
}
};
template <typename BASE>
class Parent: public BASE {
public:
int addparent() {
//Here we have to add a new child among others
this->addchild();
}
};
int main() {
Child child1;
child1.addchild();
Parent<Child> parent1;
parent1.addparent();
}
答案 1 :(得分:0)
在当前设计中无法完成。您要么需要在Child
类中拥有一个Parent
对象,要么将一个Child
对象作为参数传递给addparent()
函数。
class Parent: public User {
private:
Child child; //Have an instance of Child class here to be able
//to use addchild() in this class
public:
int addparent() {
//Here we have to add a new child among others
child.addchild();
}
};
或传递这样的参数:
class Parent: public User {
private:
Child child; //Have an instance of Child class here to be able
//to use addchild() in this class
public:
int addparent(Child & child) {
child.addchild();
}
};
我不确定您如何组织整个班级以及打算如何与他们一起工作。
通过https://www.tutorialspoint.com/design_pattern/design_pattern_overview.htm
探索设计模式此外,在http://www.learncpp.com/cpp-tutorial/102-composition/
中查找C ++中的组合概念这可能会帮助您提出更好的设计。