如何让子类对象随构造传入的父类对象数据变更同步更新?
问题分析
你当前的代码中,Human构造函数接收Entity参数时用的是值传递,这会生成一个Entity的临时副本。Human只是把这个副本的life值复制到自身继承的Entity成员变量里,所以Hero、Villain和Human_data是三个完全独立的Entity实例,修改Human_data的life自然不会影响另外两个。
要实现同步更新,必须让所有Human对象共享同一个Entity实例的内存空间,这就需要用引用或指针来持有这个对象,而不是拷贝。
方案1:使用引用持有共享的Entity(推荐,更安全)
这里保留Entity作为Human父类的设计,同时让Human持有共享Entity的引用,所有状态访问都通过该引用实现同步:
#include <iostream> #include <string> using namespace std; class Entity{ private: int life; public: Entity() : life(100) {} Entity(int life) : life(life) {} int get_life() const { return life; } void set_life(int new_life) { life = new_life; } void print_life() const { cout << "This entity has " << life << " life" << endl; } }; class Human : public Entity{ private: Entity& shared_entity; // 持有共享的Entity引用 public: string name; // 引用必须在构造函数初始化列表中完成绑定 Human(string name, Entity& entity) : shared_entity(entity), name(name) {} // 重写print_life,使用共享Entity的状态 void print_life() const { cout << name << " has " << shared_entity.get_life() << " life" << endl; } // 统一通过共享Entity访问life int get_life() const { return shared_entity.get_life(); } }; int main(){ Entity Human_data(50); Human Hero("Steve", Human_data); Human Villain("Mike", Human_data); Human_data.set_life(5000); Hero.print_life(); // 输出:Steve has 5000 life Villain.print_life(); // 输出:Mike has 5000 life return 0; }
方案2:使用指针持有共享的Entity
如果需要后续更换共享的Entity对象,可以用指针实现,同时注意空指针安全:
#include <iostream> #include <string> using namespace std; class Entity{ private: int life; public: Entity() : life(100) {} Entity(int life) : life(life) {} int get_life() const { return life; } void set_life(int new_life) { life = new_life; } void print_life() const { cout << "This entity has " << life << " life" << endl; } }; class Human : public Entity{ private: Entity* shared_entity; // 持有共享的Entity指针 public: string name; Human(string name, Entity* entity) : shared_entity(entity), name(name) {} void print_life() const { if(shared_entity) { cout << name << " has " << shared_entity->get_life() << " life" << endl; } } int get_life() const { return shared_entity ? shared_entity->get_life() : Entity::get_life(); } // 支持后续更换共享的Entity void set_shared_entity(Entity* entity) { shared_entity = entity; } }; int main(){ Entity Human_data(50); Human Hero("Steve", &Human_data); Human Villain("Mike", &Human_data); Human_data.set_life(5000); Hero.print_life(); // 输出:Steve has 5000 life Villain.print_life(); // 输出:Mike has 5000 life return 0; }
关键说明
- 引用和指针的核心是让所有
Human对象指向同一个内存地址的Entity实例,修改原对象时,所有引用它的Human都会读取到最新值。 - 使用引用时,必须在构造函数初始化列表中完成绑定,且绑定后无法更改指向,适合固定共享同一个对象的场景。
- 使用指针时,可以后续更换指向的
Entity,但需要额外处理空指针的安全问题。
内容的提问来源于stack exchange,提问作者Leonard-Florentin SANDU
相关产品推荐
相关产品推荐

