将类的属性泄漏到其组件

Leaking attributes of class to it's components

本文关键字:组件 泄漏 属性      更新时间:2023-10-16

我有以下类:

class A {
    // Whatever
};
class B {
    T attribute;
    A a;
};

现在假设我有以下场景:

A aX, aY;  
B bX, bY;  

现在我可以将aXaY"插入"bXbY中。

我想让A型的对象知道,它们在B中,或者换句话说,它们的"超类"B的"attribute"是什么。

问题:

我希望能够在它们的"超类"B 之间自由移动 A 类型的对象,我需要一种方法在运行时动态地将 B 的属性泄漏给它们,以便类型 A 的对象始终知道它们属于哪个 B(或者它们当前所在的 B 的属性是什么)。

最好的方法是什么?

也许这很有用(从所有者指向属性的指针,反之亦然):

class A;
class B {
    T attribute;
    A* a;
public:
   void setA(A* newA);
   T getAttribute() {return attribute;}
   void setAttribute() {/*some code*/}
};
class A {
   B* Owner;
   friend void B::setA(A* newA);
public:
    void setOwner(B* newOwner) {
        newOwner->setA(this);
    }
};
void B::setA(A* newA)
{
    A* tempA = this->a;
    B* tempB = newA->Owner;
    tempA->Owner = NULL;
    tempB->a = NULL;
    this->a = newA;
    newA->Owner = this;
}

更新:修复了循环指向和循环调用中的一个错误,它只能通过朋友函数来解决。

你可以做的一件事是给A一个指向它B"父"的指针:

class A {
public:
  A() : b_(0) {}
  explicit A(B* parent) : b_(parent) {}
private:
  B* b_;
};
class B {
  B() : a(this) {}
};

将"B"类定义为接口。创建"getAttribute"方法并将"B"的指针设置为"A"类的实例。现在,您可以制作"B"类的孩子并向其添加"A"类,并且"A"类始终可以知道"B"的属性。

class A 
{
    // Whatever
    B* pointerToB;
    void setB(B* b){ pointerToB = b; }
};
class B 
{
    virtual void someMethod() = 0;
    void addA(A* a)
    {
       a->setB(this);
       this->a = *a;
    }  
    T getAttribute(){ return attribute; }
    T attribute;
    A a;
};
class BB : public B {} // define BB's someMethod version or more method's

您可以在 A 中设置指向 B 的指针,并使用对 A 的引用 B 直接从 A 对象获取所需的内容:

#include <iostream>
class B;
class A {
    B *_b;
public:
    void setB(B *b) {
        _b = b;
    }
    B *getB() {
        return _b;
    }
};
class B {
    int _attribute;
    A &_a;
public:
    B(A& a, int attribute) : _attribute(attribute), _a(a) {
        _a.setB(this);
    }
    int getAttribute() {
        return _attribute;
    }
};
int main(int argc, const char *argv[])
{
    A a1;
    B b1(a1, 5);
    A a2;
    B b2(a2, 10);
    std::cout << a1.getB()->getAttribute() << std::endl;
    std::cout << a2.getB()->getAttribute() << std::endl;
    return 0;
} 

输出:

5
10