我想使用5个特定的类来设计结构:Person,Driver,Employee,Child和Parent。

-每个驾驶员都是一个人。

-每个员工既是司机又是一个人。

-每个孩子都是一个人。

-每个父母都是一个人,司机,雇员,并且可以有一个或多个孩子。

这就是我的想法:

class Parent {
public:
    class Employee {
    public:
        class Driver {
        public:
            class Person {
                string name;
                int age;
            public:
                string GetName() { return name; }
                void SetName(string name) { this->name = name; }
                int GetAge() { return age; }
                void SetAge(int age) { this->age = age; }
            };
        private:
            Person person;
            string carName;
        public:
            Person GetPerson() { return person;}
            void SetPerson(Person person) { this->person = person;}
            string GetCarName() { return carName; }
            void SetCarName(string carName) { this->carName = carName;}
        };
    private:
        Driver driver;
    public:
        Driver GetDriver() { return driver; }
        void SetDriver(Driver driver) { this->driver = driver; }
    };
    class Child {
    public:
        class Person:public Employee::Driver::Person {
        };
    private:
        Person person;
        string nameOfSchool;
    public:
        Person GetPerson() { return person; }
        void SetPerson(Person person) { this->person = person;}
        string GetNameOfSchool(){ return nameOfSchool;}
        void SetNameOfSchool(string nameOfSchool) { this->nameOfSchool = nameOfSchool;}
    };
private:
    Employee employee;
    Child child;
public:
    Employee GetEmployee() { return employee; }
    void SetEmployee(Employee employee) { this->employee = employee;}
    Child GetChild() { return child;}
    void SetChild(Child child) { this->child = child;}
};


但是当我尝试类似的东西时:

Parent random_parent;
    random_parent.GetEmployee().GetDriver().GetPerson().SetName("Joseph");
    random_parent.GetEmployee().GetDriver().GetPerson().SetAge(80);
    cout << random_parent.GetEmployee().GetDriver().GetPerson().GetName() << endl << random_parent.GetEmployee().GetDriver().GetPerson().GetAge();


我得到的只是这个垃圾值:

-858993460


如何使Parent的任何实例正常工作,并能够从内部类name访问和初始化agePerson

最佳答案

GetPersonGetDriverGetChildGetEmployee应该返回引用或指针。现在,当您调用random_parent.GetEmployee()时,它将返回一个全新的临时Employee对象,该对象是random_parent中的副本。如果执行random_parent.GetEmployee().SetDriver(new_driver),则它将驱动程序设置在此全新的Employee对象中,而不是在random_parent中的驱动程序中。语句执行后,临时Employee对象将被丢弃。

如果你改变

Employee GetEmployee() { return employee; }




//     here
//      |
//      V
Employee& GetEmployee() { return employee; }


然后random_parent.GetEmployee()将返回对employeerandom_parent对象的引用。 random_parent.GetEmployee().SetDriver(new_driver);将更新该对象,这就是您期望发生的情况。

GetDriverGetPersonGetChild执行相同的操作。



这可以解决您的直接问题。但是,您的代码设计不佳。您可以在Code Review上获得设计建议。

关于c++ - 如何使用包含内部类的类的实例有效地从内部类访问成员?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59210592/

10-11 02:14