如何创建具有基于构造函数中传递的另一个对象的数据的变量的对象



标题可能有点令人困惑,但请听我说完。我有两个类,实体和人类。实体是人的父类。当我创建一个人类对象时,它将需要一个实体对象作为构造函数的参数传递,这样我创建的所有人类对象都具有相同的实体对象信息。

这是我的问题:如果我改变了实体对象中的一些数据,我想要更新我在构造函数中使用该实体对象创建的人类对象中的所有数据。

我想在我的一个大学项目中实现这一点,所以我只允许使用标准库。我写这个例子是为了更容易理解:

#include <iostream>
using namespace std;
class Entity{
private:
//DATA
int life;
public:
//DEFAULT CONSTRUCTOR
Entity() {life = 100;}
//PARAMETRIZED CONSTRUCTOR
Entity(int life) {this -> life = life;}
//GETTER
int get_life(){return life;}
//SETTER
void set_life(int new_life){life = new_life;}
//FUNCTIONS
void print_life() {cout << "This entity has " << life << " life" << endl;}
};
class Human : public Entity{
public:
//DATA
string name;
//DEFAULT CONSTRUCTOR
Human() {name = "N/A";}
//PARAMETRIZED CONSTRUCTOR
Human(string name, Entity object){
Entity::set_life(object.get_life());
this -> name = name;
}
};
int main(){
//DATA
Entity Human_data(50);
Human Hero("Steve", Human_data);
Human Villain("Mike", Human_data);
//BODY
Human_data.set_life(5000);
Hero.print_life();

//END MAIN
return 0;}

正如你所看到的,在我将人类数据生命从50更新到5000之后,它不会同时将英雄和恶棍的生命更改为5000,而只是将人类数据生命更改为5000。

我假设当你调用Human_data.set_life(5000)时,你想影响所有用Human_data对象构造的Human对象。

这里有一个如何使用引用的例子。但请注意,将引用放入类中并非没有后果。您可以使用指针,或者更好的是智能指针。但我只是想说明一下大意。

从技术上讲,使用引用意味着你必须习惯使用初始化列表,因为引用不能被赋值。

#include <iostream>
using namespace std;
class Entity{
private:
int life;
public:
Entity() : life(100) {}
Entity(int life) : life(life) {}
int get_life() {return life;}
void set_life(int new_life){life = new_life;}
void print_life() {cout << "This entity has " << life << " life" << endl;}
};
class Human { // no inheritence
private:
Entity& entity; // store a reference to the entity
public:
string name;
Human(string name, Entity& object) // object is a reference
: entity(object), name(name)
{
}
void print_life() { entity.print_life(); } // forward to entity
};
int main(){
//DATA
Entity Human_data(50);
Human Hero("Steve", Human_data);
Human Villain("Mike", Human_data);
//BODY
Human_data.set_life(5000);
Hero.print_life();
//END MAIN
return 0;
}

继承可能是正确的,如果所有的"人";Are也是实体(记住继承是"is "关系)。

但是实现是有缺陷的。

Entity对象传递给Human构造函数,并使用单独的Entity对象来控制"生命",而是将生命本身传递给Human构造函数,并直接在Human对象上使用set_life

像这样:

class Human : public Entity
{
public:
// By default humans start out with 50 in life
Human(std::string const& name, int life = 50)
: Entity(life), name(name)  // Initialize the parent class, then the name
{
}
private:
std::string name;
};
int main()
{
Human hero("The Hero", 5000);  // The hero will have 5000 life
Human villain("The Villain");  // The villain will only have 50 life
// Some stuff...
// Update the heroes life
hero.set_life(4000);  // Uh oh, the hero have lost 1000 life!
// ...
}

最新更新