C ++中的循环依赖问题

InQ*_*ive 3 c++

我今天在处理复杂库时遇到的一个极简循环依赖问题如下

class Something; 

class Test
{
   public:
   int i;
   void process()
   {
     Something S;
     S.doSomething();
   }
};

class Something
{
   public:
   void doSomething()
   {
     Test t;
     t.i = 10;
   }
};

int main()
{
   Test t;
   t.process();
}
Run Code Online (Sandbox Code Playgroud)

test.cxx:10:16:错误:聚合“ S事物”类型不完整,无法定义。

使这项工作最少的代码更改是什么?重新排列Testor Something类只会交换错误。我可以想到的一个方法是使用全局/静态函数,doSomething()其中的操作与Test t对象有关。有什么更好的方法?

Kam*_*Cuk 5

因为只有实现依赖于另一个类,所以将它们移出类定义很容易。

在单个源文件中,仅用于在Test::process定义后移动定义class Something

class Test
{
   public:
   int i;
   void process();
};

class Something
{
   public:
   void doSomething()
   {
     Test t;
     t.i = 10;
   }
};

// a function defined inside its class definition is an inline member function
inline
void Test::process()
{
    Something S;
    S.doSomething();
}

int main()
{
   Test t;
   t.process();
}
Run Code Online (Sandbox Code Playgroud)