两个类互相使用

时间:2014-02-11 03:38:41

标签: 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;
}

1 个答案:

答案 0 :(得分: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;
}