将类的属性泄漏到其组件
Leaking attributes of class to it's components
我有以下类:
class A {
// Whatever
};
class B {
T attribute;
A a;
};
现在假设我有以下场景:
A aX, aY;
B bX, bY;
现在我可以将aX
或aY
"插入"bX
或bY
中。
我想让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
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- 如何将 txt 文件中的行分隔为组件C++
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 尽管遵循了规则,内存泄漏在哪里
- 到连接组件算法的问题(递归)
- 为什么调用堆栈数组会导致内存泄漏
- 两个 COM 组件中 ENUM 的重复条目
- 为什么 gcc 会产生这种奇怪的组件与叮当声?
- 使用 bfs 解决连接组件问题时得到错误的答案
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- 如何在ECS框架中更新组件数据和通知系统
- Klocwork Inside的资源泄漏
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 将类的属性泄漏到其组件