代码之家  ›  专栏  ›  技术社区  ›  Ivan

基于继承更改对象类型

  •  0
  • Ivan  · 技术社区  · 6 年前

    我有班上的人:

    class Person {
    public:
        int Age;
        int ID;
    };
    

    我有两个班:成人和儿童继承人:

    class Child : Person{
    public:
        Child();
        void print_ms_child(){
            cout << "I'm an child";
        }
    };
    
    class Adult : Person{
    public:
        Adult(); 
        void print_ms_Adult(){
            cout << "I'm an adult";
        }
    };
    

    int main() {
        Person my_Person;
        my_Person.Age = 10;
        my_Person.ID = 013272;
    

    然后使用条件设置其类型。

        if(my_Person.Age > 18){
            my_Person = new Adult(); // this won't work
        }
        else{
            my_Person = new Child(); // this won't work
        }
    

    我想这是可能的,但我不知道正确的语法(

    但是 ,我想从孩子变成人,以防年龄变化(我甚至不确定这是否可能)。

        my_Person.Age = 21;
        my_Person = new Adult(); // this won't work
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   jfMR    6 年前

    我先给你的班级下个定义 Person 而是这样:

    class Person {
        int Age;
        int ID;
    protected:
       Person(int age, int id): Age{age}, ID{id} {}
    public:
       virtual ~Person() = default;
    };
    

    也就是说, 的构造函数已生成 protected 因此层次结构之外的类不能创建 virtual 使其适合作为多态类型的基类。

    那么,两者 Child Adult 公开继承 ,因为你已经有了它们。他们的构造器最终调用 具有与其构造函数接收的相同参数化的构造函数:

    class Adult: public Person {
    public:
       Adult(int age, int id): Person(age, id) {}
       // ...
    };
    
    class Child: public Person {
    public:
       Child(int age, int id): Person(age, id) {}
       // ...
    };
    

    最后,为了创建从 ,我将创建

    std::unique_ptr<Person> create_person(int age, int id) {
       if (age < 18)
          return std::make_unique<Child>(age, id);
       else
          return std::make_unique<Adult>(age, id);
    }
    

    儿童 成人 反对。在运行时确定要创建的对象的类型。


    你想知道 对象可能成为

    我建议把 不变的 因此,每当一个人的年龄增加时,就必须创造一个新的物体。这样,从现有对象创建新对象将成为 在那一刻,你将有权决定是否创建一个 儿童 成人

    为此,首先,请确认 Age 数据成员 作为 const (你也可以 ID ). 然后,定义以下内容 的成员函数,它总是创建一个新对象(具有相同的 身份证件 )由于增加了 年龄 一个人:

    std::unique_ptr<Person> Person::increase_age() const {
       return create_person(Age + 1, ID);
    }
    

    如您所见,它将对象的创建委托给工厂函数, create_person() 儿童 对象,因为它继承自 .

        2
  •  0
  •   Jesper Juhl    6 年前

    不能在变量声明后更改其类型。C++是一个 . my_person 是一个 Person