包括“交换”

时间:2014-02-18 23:08:28

标签: c++ oop c++11

正如你所看到的,标题有点废话,这是因为我真的不知道怎么称呼它,但知道我努力寻找更好的标题。 我希望你能理解我想要看到的其他问题。

我们假设我有3个班级,“A”,“B”和“C”。

  

“A”类包括“B”和“C”。

     

“B”类包括“A”

     

“C”类包括“A”

我们去代码......

#include <iostream>
#include <b.hpp>
#include <c.hpp>
class A
{
public:
    A()
    {
        std::cout << "Hello from A" << std::endl;
        A a;
        B b;
    }
};

#include <iostream>
#include <a.hpp>
class B
{
public:
    B()
    {
        std::cout << "Hello from B" << std::endl;
    }
};

#include <iostream>
#include <a.hpp>
class C
{
public:
    C()
    {
        std::cout << "Hello from C" << std::endl;
    }
};

这样,一切正常,输出:

  

你好   B你好   你好,来自C

但是,如果我这样做:

#include <iostream>
#include <a.hpp>
#include <vector>
class B
{
public:
    B()
    {
        std::cout << "Hello from B" << std::endl;
    }
private:
    std::vector<A> garage;
};

我遇到了一连串的错误,包括这个错误(实际上,主要的错误,因为那个,还有其他错误):

  

错误:未在此范围内声明'A'

     

std :: vector garage;

这正是我想要的,你知道我能做什么吗?谢谢。

@edit - 回答@Kerrek SB

我尝试为每个文件,标题和来源创建单独的文件。 (.hpp和.cpp)并且错误仍然存​​在。

A.hpp

#ifndef A_HPP
#define A_HPP

#include <iostream>
#include <B.hpp>
#include <C.hpp>

class A
{
public:
    A();
};

#endif

A.cpp

#include <A.hpp>

A::A()
{
    std::cout << "Hello from A" << std::endl;
    B b;
    C c;
}

B.hpp

#ifndef B_HPP
#define B_HPP

#include <iostream>
#include <A.hpp>
#include <vector>

class B
{
public:
    B();
private:
    std::vector<A> garage;
};

#endif

B.cpp

#include <B.hpp>

B::B()
{
    std::cout << "Hello from B" << std::endl;
}

C.hpp

#ifndef C_HPP
#define C_HPP

#include <iostream>
#include <A.hpp>

class C
{
public:
    C();
};

#endif

C.cpp

#include <C.hpp>

C::C()
{
    std::cout << "Hello from C" << std::endl;
}

的main.cpp

#include <iostream>
#include <A.hpp>

int main(int argc, char ** argv)
{
    A a;
    return 0;
}

GCC

  

g ++ -O2 -std = c ++ 11 -I“。” -o exchange A.cpp B.cpp C.cpp main.cpp

输出

  

包含在./A.hpp:5:0的文件中,

             from ./C.hpp:5,

             from C.cpp:1:
     

./ B.hpp:13:17:错误:未在此范围内宣布'A'

 std::vector<A> garage;

1 个答案:

答案 0 :(得分:3)

将类定义与类成员定义分开:

#include <iostream>
#include <vector>

class A { public: A(); };
class B { public: B(); private: std::vector<A> garage; };
class C { public: C(); };

A::A()
{
    std::cout << "Hello from A" << std::endl;
    // A a;  // no, because that's idiotic
    B b;
}

B::B()
{
    std::cout << "Hello from B" << std::endl;
}

C::C()
{
    std::cout << "Hello from C" << std::endl;
}

在较大的项目中,您可能会为每个项目分别设置标题和源文件。