1 c++ oop containers design-patterns
在当前对象由其他包含的对象操作的系统中,当传递对当前对象的引用时,看起来链接继续......并且没有任何结束(对于下面的代码,Car->myCurrentComponent->myCar_Brake->myCurrentComponent->myCar_Brake->myCurrentComponent....).
我Car和Car->myCurrentComponent->myCar_Brake指同一个地址,指向同一个对象.这就像Car包含Brake指的是Car.
事实上,Car是唯一的对象,myCar_Brake和myCar_Speed只是引用(指向)它.这种使用引用和指针是否正常?这种方法有任何潜在的问题吗?
示例代码
class Brake
class C
class   Car
{
public:
Car();
// Objects of type B and C.
Brake*  myBrake;
Speed*  mySpeed;
// Current component under action.
Component*  myCurrentComponent;
}
/******************************/
// Constructor
Car::Car()
{
myBrake = new Brake(*this);
mySpeed = new Speed(*this);
myCurrentComponent = myBrake;
}
/******************************/
class   Brake: public   Component
{
public:
Brake(Car&);
// Needs to operate on A.
Car*    myCar_Brake;
}
// Constructor
Brake::Brake(Car&)
{
myCar_Brake = Car;
}
/******************************/
class Speed
{
public:
Speed(Car&);
// Needs to operate on A.
Car*    myCar_Speed;
}
// Constructor
Speed::Speed(Car&)
{
myCar_Speed = Car;
}
/****************************/
在对象图中使用循环引用没有根本问题,只要您理解并且不试图遍历对象图而不跟踪您遇到的对象.要专门回答你的问题,在对象之间进行循环引用是比较常见的; 例如,它是双向链表的工作方式.