C++ 继承和指向受保护成员的指针
我目前正在为我正在编写的游戏创建一个基本的UI系统。它被组织成一个节点树。我正在尝试编写它,以便只有根节点可以在其他节点上调用update方法。我想我理解C++继承,但它再次嘲笑我的无能。我已经尝试创建了下面一个简单的示例:C++ 继承和指向受保护成员的指针,c++,pointers,inheritance,access-control,protected,C++,Pointers,Inheritance,Access Control,Protected,我目前正在为我正在编写的游戏创建一个基本的UI系统。它被组织成一个节点树。我正在尝试编写它,以便只有根节点可以在其他节点上调用update方法。我想我理解C++继承,但它再次嘲笑我的无能。我已经尝试创建了下面一个简单的示例: class Base { public: virtual ~Base() { } protected: virtual void update_internal() = 0; }; class Node_A : publi
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();
}
包括root在内的所有节点都从Base继承update_internal()方法,我不明白为什么它受到保护很重要。我认为只有私有成员和方法是派生类无法访问的。您只能从派生类的实例调用基类的受保护/私有函数(当然,除非您使用
friend
s)。因此,派生类只能访问其基部分的私有/受保护成员,而不能访问其他基部分的私有/受保护成员。在您的例子中,您可以通过引用中的Base*
来调用它
for(auto& node : m_nodes)
node->update_internal();
因此编译器会抱怨。只需与Base和Root交朋友
class Base
{
friend class Root; // <- yes,this
public:
virtual ~Base() { }
protected:
virtual void update_internal() = 0;
};
类基
{
friend类Root;//这是该模式的一个常用示例。
Root
类的公共方法公开了需要在内部实现的内容。类基
class Base
{
protected:
virtual void update_internal() = 0;
static void DoUpdate( Base *node )
{
node->update_internal();
}
};
class Root : public Base
{
public:
void update()
{
for (auto node : m_nodes)
{
Base::DoUpdate( node );
}
}
protected:
virtual void update_internal() override {}
std::vector<Base*> m_nodes;
};
{
受保护的:
虚拟无效更新_internal()=0;
静态void更新(基本*节点)
{
节点->更新_internal();
}
};
类根:公共基
{
公众:
无效更新()
{
用于(自动节点:m_节点)
{
Base::DoUpdate(节点);
}
}
受保护的:
虚拟无效更新_internal()重写{}
std::向量m_节点;
};
class Base
{
protected:
virtual void update_internal() = 0;
static void DoUpdate( Base *node )
{
node->update_internal();
}
};
class Root : public Base
{
public:
void update()
{
for (auto node : m_nodes)
{
Base::DoUpdate( node );
}
}
protected:
virtual void update_internal() override {}
std::vector<Base*> m_nodes;
};