【发布时间】:2016-02-29 20:46:58
【问题描述】:
我目前正在为我正在编写的游戏创建一个基本的 UI 系统。它被组织成一棵节点树。我正在尝试编写它,以便只有根节点可以调用其他节点上的更新方法。我以为我了解 C++ 继承,但它再次嘲笑我的无能。我尝试在下面创建一个简单的示例:
class Base
{
public:
virtual ~Base() { }
protected:
virtual void update_internal() = 0;
};
class Node_A : public Base
{
protected:
virtual void update_internal() { std::cout << "Update Node A" << std::endl; }
};
class Node_B : public Base
{
protected:
virtual void update_internal() { std::cout << "Update Node B" << std::endl; }
};
class Root : public Base
{
public:
void add_node (Base* node) { m_nodes.push_back(node); }
void update()
{
for (auto& node : m_nodes)
{
node->update_internal();
}
}
protected:
std::vector<Base*> m_nodes;
virtual void update_internal() { }
};
int main()
{
Node_A alpha_node;
Node_B beta_node;
Root root_node;
root_node.add_node(&alpha_node);
root_node.add_node(&beta_node);
root_node.update();
}
当我尝试编译这个 GCC 时出现错误:
error: 'virtual void Base::update_internal()' is protected
包括 root 在内的所有节点都从 Base 继承 update_internal() 方法,我不明白为什么它受到保护很重要。我以为只是派生类无法访问的私有成员和方法。
【问题讨论】:
标签: c++ pointers inheritance access-control protected