gpt4 book ai didi

c++ - C++继承中,派生类如何禁用基类的某些元素(数据或函数)?

转载 作者:太空狗 更新时间:2023-10-29 23:27:51 25 4
gpt4 key购买 nike

例如,假设现在我们有两个类,Tree(基类)和 BinaryTree(派生类)。类 Tree 具有数据子级和函数 getChildren()。

class Tree {
public:
vector<int> getChildren();
...
private:
vector<int> children;
...
};

派生类有数据leftChild和rightChild,以及getLeftChild()和getRightChild()函数。

class BinaryTree : public Tree {
public:
int getLeftChild();
int getRightChild();
...
private:
int leftChild;
int rightChild;
...
};

当然,数据子项和函数 getChildren() 不是我们想要的派生类。我们可能根本不使用它们,但它们仍然存在。那么如何在派生类中禁用这些元素呢?

谢谢

最佳答案

您面临的主要问题是关于概念,而不是编程。

Tree 中,您可以通过调用 getChildren() 获取子节点,并且您可以对 BinaryTree 使用相同的方法,区别在于BinaryTree::getChildren 将只返回两个 child ,右边和左边。

如果一个 BinaryTree 是一个(特殊的)Tree,那么您有一个特殊版本的 GetChildren 是完全可以的。

如果您不希望基类成员存在于派生类中,则将它们设为私有(private),如果您希望它们公开,则必须考虑使用组合而不是继承

关于c++ - C++继承中,派生类如何禁用基类的某些元素(数据或函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27658752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com