C++ 类 成员相互引用并被使用
C++ classes with members referencing each other and being used
我有 2 个 c++ 类,其中的成员相互引用。我正在调用引用 类 的成员,所以我不能使用前向声明,因为我收到错误 "pointer to incomplete class type is not allowed"
class A {
B* b;
void foo() {
b->do_something();
}
};
class B {
A* a;
void bar() {
a->do_something_else();
}
};
有什么方法可以让包含在这里工作吗?
已经有一个类似名称的工单,但我无法使用那里的解决方案。
只需将定义与声明分开:
class B;
class A {
public:
void foo();
void do_something_else(){}
private:
B* b;
};
class B {
public:
void bar();
void do_something(){}
private:
A* a;
};
//now B has a complete type, so this is fine
void A::foo() {
b->do_something();
}
//ditto
void B::bar() {
a->do_something_else();
}
您可以在头文件中使用原型定义。以及cpp文件中的逻辑体。
这样做之后你可以在头部使用前向声明(class B, class A)
示例:@TartanLlama
我有 2 个 c++ 类,其中的成员相互引用。我正在调用引用 类 的成员,所以我不能使用前向声明,因为我收到错误 "pointer to incomplete class type is not allowed"
class A {
B* b;
void foo() {
b->do_something();
}
};
class B {
A* a;
void bar() {
a->do_something_else();
}
};
有什么方法可以让包含在这里工作吗?
已经有一个类似名称的工单,但我无法使用那里的解决方案。
只需将定义与声明分开:
class B;
class A {
public:
void foo();
void do_something_else(){}
private:
B* b;
};
class B {
public:
void bar();
void do_something(){}
private:
A* a;
};
//now B has a complete type, so this is fine
void A::foo() {
b->do_something();
}
//ditto
void B::bar() {
a->do_something_else();
}
您可以在头文件中使用原型定义。以及cpp文件中的逻辑体。
这样做之后你可以在头部使用前向声明(class B, class A)
示例:@TartanLlama