C++ C++;调用另一个子类的公共方法
是否有一个优雅的版本来访问另一个子类的方法? 为了更好的理解,请看我的C++代码。 外部函数/类可以访问addchild()方法,这一点非常重要 C++代码:C++ C++;调用另一个子类的公共方法,c++,oop,C++,Oop,是否有一个优雅的版本来访问另一个子类的方法? 为了更好的理解,请看我的C++代码。 外部函数/类可以访问addchild()方法,这一点非常重要 C++代码: class User { protected: int userid; std::string givenname; std::string surname; std::string birthday; }; class Child: public User {
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();
}
统一建模语言:
您可以将CRTP用于父类:(更一般:) 因为它没有引起注意,所以我更改了原始代码示例,以便它使用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();
}
#包括
类用户{
受保护的:
int用户标识;
std::字符串givenname;
std::字符串姓氏;
字符串生日;
};
类子级:公共用户{
公众:
int addchild(){
//执行添加新子级所需的操作
}
};
模板
父类:公共基{
公众:
int addparent(){
//在这里,我们必须添加一个新的孩子
这个->addchild();
}
};
int main(){
儿童1;
child1.addchild();
父母1;
parent1.addparent();
}
在当前设计中无法执行此操作。您需要在Parent
类中有一个Child
对象,或者将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();
}
};
我不知道你是如何组织你的整个班级的,你打算用他们做什么
探索设计模式
也可以在
中查找C++中的构词概念这可能会帮助你想出更好的设计。你说的“优雅”是什么意思?根据您的图表,
父项
不应该有关于子项
存在的信息。无法执行此操作。你要么给Parent
它自己定义的addChild()
,要么让Parent
从定义addChild()
@Yksisarvinen的基类派生出来是的,我知道!这是我的问题,我怎样才能在他们之间建立关系?恐怕我不理解你的问题。您希望父类
类中包含子类
类的某些对象吗?因为您需要Child
类的对象来调用其上的方法addChild()
。这很容易做到,只需提供Child
类实例来调用int addparent(Child&Child){Child.addChild();}