如何使用包含内部类的类实例有效地从内部类访问成员?
How can I efficiently access members from inner classes using instances of a class which includes inner classes?
我想使用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
访问和初始化name
和age
?
在设计方面,驾驶员、员工、子项和父项不是人员的后代。它们是角色,一个人可以拥有任意数量的角色。或者,它们可以是两个人之间的关系,例如,一个人是一个人的孩子,另一个人是父母。
GetPerson
、GetDriver
、GetChild
和GetEmployee
应该返回引用或指针。现在,当你调用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_parent
中employee
对象的引用。random_parent.GetEmployee().SetDriver(new_driver);
将更新该对象,这是您期望发生的情况。
对GetDriver
、GetPerson
和GetChild
执行相同的操作。
这可以解决您的直接问题。但是,您的代码设计不佳。您可以获得有关代码审查的设计建议。
- 从模板化父类中的派生内部类访问受保护的成员变量
- C++模板类的内部类访问
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 内部类私有成员访问和封闭的友好性
- 从内部类访问外部公共成员
- 从内部类访问外部类,而无需明确传递实例
- clang或gcc关于这个内部类成员访问是否正确
- C++ 内部类无法访问外部类的成员
- 类内类访问外部类的数据成员
- C++:如何访问内部类的方法
- 如何从其他类访问数据私有内部类
- 派生类是否可以访问作为内部类的好友的父类的受保护内部类的私有方法
- C++ 外部类访问 内部类为什么被禁止
- 无法访问 C++ 中的内部类
- 通过外部类的实例访问嵌套的内部类
- 内部类访问外部类嵌套枚举
- 当内部类是class vs struct时,不可访问的基类
- 从外部类访问嵌套的内部类结构
- 无法使用外部类对象访问内部类成员
- 内部类访问