[英]C++ structs Interdependency
Hello i have structures declared in the same Header file that need eachother. 您好,我在同一个Header文件中声明了需要互相使用的结构。
struct A; // ignored by the compiler
struct B{
A _iNeedA; //Compiler error Here
};
struct A {
B _iNeedB;
};
this work normally 这项工作正常
class A;
class B{
A _iNeedA;
};
class A {
B _iNeedB;
};
// everything is good
Thank you very much! 非常感谢你!
This can't work: A
contains B
contains A
contains B
contains …. 这行不通:
A
包含B
包含A
包含B
包含…。 Where to stop? 在哪里停下来?
All you can do to model cyclic dependencies is use pointers: 您可以为循环依赖关系建模的所有方法是使用指针:
class A;
class B {
A* _iNeedA;
};
class A {
B* _iNeedB;
};
Now the classes don't contain each other, merely references to each other. 现在,这些类不再包含彼此,而只是相互引用。
Furthermore, you need to pay attention that you can't use things you haven't defined yet: in the above code, you have declared A
before defining B
. 此外,您还需要注意不能使用尚未定义的内容 :在上面的代码中,在定义
B
之前已声明 A
So it's fine to declare pointers to A
in B
. 因此,可以在
B
声明指向 A
指针 。 But you cannot yet use A
before defining it. 但是在定义它之前您还不能使用
A
I answer my own question. 我回答我自己的问题。
the fact is what im doing is not exactly what i posted but i thougt it was the same thing, actually i'm using operators that take arguments. 事实是我在做什么并不完全是我发布的内容,但我是同一回事,实际上我正在使用带有参数的运算符。 Thoses operators body must be defined after my structs declarations (outside the struct), because struct B don't know yet struct A members...
这些操作符主体必须在我的结构声明之后(在结构外部)定义,因为结构B尚不知道结构A成员...
I said it was working with classes because with classes we usualy use CPP file for methods definition, here i am not using any cpp file for methods i use in my structs 我说它正在与类一起使用,因为对于类,我们通常使用CPP文件进行方法定义,这里我没有将任何cpp文件用于结构中使用的方法
I was about to delete this post but you guys are too fast ;), 我本打算删除这篇文章,但是你们太快了;),
Here an example 这是一个例子
struct A;
struct B {
int member;
bool operator<(const A& right); //body not defined
};
struct A {
int member;
bool operator<(const B& right)
{
return this->member < B.member;
}
};
bool B::operator<(const A& right) //define the body here after struct A definition
{
return this->member < A.member;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.