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

标签 c++ inheritance

例如,假设现在我们有两个类,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/

相关文章:

c++ - 简单的 c strtok_r 测试中的内存紊乱

c++ - 我可以使用在 CUDA 内核中实现纯虚函数的类吗?

java - 无法在 SWIG 包装器中公开私有(private)基类成员函数

sql - PostgreSQL 删除失败,继承表上有 ON DELETE 规则

php - OOP如何管理存储在不同文件中的 'include'类

C++ map 中出现频率最高的元素

c++ - 使用 TBB 插入一个无序的 boost bimap

Multimap 上的 C++ 泛型编程

python - Python 3 中是否有类似于 C++ 中的 getchar() 的内置函数?

c++ - 虚拟继承是如何工作的?