如何使用包含内部类的类实例有效地从内部类访问成员?

How can I efficiently access members from inner classes using instances of a class which includes inner classes?

本文关键字:内部类 访问 成员 有效地 何使用 包含 实例      更新时间:2023-10-16

我想使用5个特定的类设计一个结构:人,司机,员工,孩子和父母。

-每个司机都是一个人。

-每个员工既是司机,也是人。

-每个孩子都是一个人。

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

以下是我的想法:

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的任何实例工作并能够从内部类Person访问和初始化nameage

在设计方面,驾驶员、员工、子项和父项不是人员的后代。它们是角色,一个人可以拥有任意数量的角色。或者,它们可以是两个人之间的关系,例如,一个人是一个人的孩子,另一个人是父母。

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()将返回对random_parentemployee对象的引用random_parent.GetEmployee().SetDriver(new_driver);将更新该对象,这是您期望发生的情况。

GetDriverGetPersonGetChild执行相同的操作。


这可以解决您的直接问题。但是,您的代码设计不佳。您可以获得有关代码审查的设计建议。