【发布时间】:2011-03-23 16:22:08
【问题描述】:
更新:让我澄清一下我的文件并重申我的问题:
main.h
#include "other.h"
class MyClass
{
public:
void MyMethod();
void AnotherMethod();
OtherClass test;
}
main.cpp
#include "main.h"
void MyClass::MyMethod()
{
OtherClass otherTemp; // <--- instantitate OtherClass object
otherTemp.OtherMethod(); // <--- in this method here, is where I want to also call MyClass::AnotherMethod()
}
void MyClass::AnotherMethod()
{
// Some code
}
other.h
class OtherClass
{
public:
void OtherMethod();
}
other.cpp
#include "other.h"
void OtherClass::OtherMethod()
{
// !!!! This is where I want to access MyClass::AnotherMethod(). How do I do it?
// I can't just instantiate another MyClass object can I? Because if you look above in
// main.cpp, this method (OtherClass::OtherMethod()) was called from within
// MyClass::MyMethod() already.
}
所以基本上我想要的是:你实例化对象 A,然后实例化对象 B,它又调用来自对象 A 的方法。我确信这样的事情是可能的,但它可能只是我的设计很糟糕。任何方向将不胜感激。
【问题讨论】:
-
为什么需要在
.h访问它? -
对于同类型问题的另一个镜头,请参阅stackoverflow.com/questions/1655096/…
-
我并不是要让任何人假设我在头文件中执行我的实现。我已经重申并澄清了我最初的问题。
-
好的,你试过了吗?根据您实现它的方式,您最终可能会出现无限递归(
OtherMethod调用AnotherMethod和 ...)但这与循环依赖无关——即使您应该尽量避免循环。 -
我已经更新了我的答案以解决对另一个方法的调用
标签: c++ include circular-dependency