C++循环引用,使用方法时出错,即使在前向声明之后也是如此
假设我有:
class B;
class A{
private:
B *b;
public:
bar(){ b->foo()};
foo();
}
class B{
private:
A *a;
public:
bar(){ a->foo();}
foo();
}
编译时此文件给出一个
错误“不完整类型结构 B 的无效使用”,
即使在我向前声明了类 B 之后也是如此。据我了解,这是因为当我在 b 上调用函数
,编译器仍然不知道这样的函数存在。我该如何解决这个问题?foo()
时
Suppose I have:
class B;
class A{
private:
B *b;
public:
bar(){ b->foo()};
foo();
}
class B{
private:
A *a;
public:
bar(){ a->foo();}
foo();
}
When compiled this file gives an
error "invalid use of incomplete type struct B",
even after I have forward declared the class B. As far as I understand it is because when I am calling the function foo()
on b
, the compiler still doesn't know that such a function exists. How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
前向声明没有提供实现细节。
A
不知道B
,只知道它存在。要解决此问题,请将声明与实现分开。
您还缺少方法的返回类型。
文件 Ah:
文件 A.cpp:
文件 Bh:
文件 B.cpp:
The forward declaration provides no implementation details.
B
is not known toA
, other than the fact that it exists.To solve this, separate your declaration from the implementation.
You're also missing return types for the methods.
File A.h:
File A.cpp:
File B.h:
File B.cpp:
将实现放在源文件中而不是标头中。
Put the implementation in a source file instead of in the header.
该错误是因为您尝试在
A::bar
中使用B
中的方法。虽然类B
已声明,但尚未定义。就像其他人说的那样,您应该将定义和实现分开,它就会起作用。
The error is because you try to use a method from
B
inA::bar
. While classB
has been declared, it has not been defined.Like the others say, you should separate the definition and the implementation, and it will work.