两个类互相使用

Val*_*tin 0 c++ circular-dependency

测试用例代码非常不言自明.所以基本上,这样的事情可以不使用.cpp文件吗?

class A
{
public:

    static int i;

    static void test(void)
    {
        std::cout << "B::i = " << B::i << std::endl;
    }
};

class B
{
public:

    static int i;

    static void test(void)
    {
        std::cout << "A::i = " << A::i << std::endl;
    }
};

int A::i = 1;
int B::i = 2;

int main(int argc, char **argv)
{
    A::test();
    B::test();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

tim*_*rau 5

定义A::test()B::test()外部.

class A
{
public:
    static int i;
    static void test(void);
};

class B
{
public:
    static int i;
    static void test(void);
};

int A::i = 1;
int B::i = 2;

void A::test(void)
{
    std::cout << "B::i = " << B::i << std::endl;
}

void B::test(void)
{
    std::cout << "A::i = " << A::i << std::endl;
}
Run Code Online (Sandbox Code Playgroud)