结构循环依赖
structure circuliar depenency
我有两个结构:
struct B;
struct A {
B *b;
void Func() {
std::cout << b->x << std::endl;
}
};
struct B {
A a;
float x;
void Func() {
a.Func();
}
};
当我尝试编译它时,出现以下错误:
Error C2027 use of undefined type 'B'
Error C2227 left of '->x' must point to class/struct/union/generic type
我该如何解决?
您可以通过将 Func
的定义从 class 声明移到 B
已完全定义的位置来解决此问题,例如:
struct B;
struct A {
B *b;
// Only declare Func, do not provide definition
void Func();
};
struct B {
A a;
float x;
void Func() {
a.Func();
}
};
// Define Func where the full definition of B is available
void A::Func() {
std::cout << b->x << std::endl;
}
我有两个结构:
struct B;
struct A {
B *b;
void Func() {
std::cout << b->x << std::endl;
}
};
struct B {
A a;
float x;
void Func() {
a.Func();
}
};
当我尝试编译它时,出现以下错误:
Error C2027 use of undefined type 'B'
Error C2227 left of '->x' must point to class/struct/union/generic type
我该如何解决?
您可以通过将 Func
的定义从 class 声明移到 B
已完全定义的位置来解决此问题,例如:
struct B;
struct A {
B *b;
// Only declare Func, do not provide definition
void Func();
};
struct B {
A a;
float x;
void Func() {
a.Func();
}
};
// Define Func where the full definition of B is available
void A::Func() {
std::cout << b->x << std::endl;
}