如你所见,这个标题有点废话,因为我真的不知道怎么调用它,但我知道我努力寻找一个更好的标题。 我希望您在看到问题的其余部分后明白我想说的是什么。
假设我有 3 个类,“A”、“B”和“C”。
The class "A" includes "B" and "C".
The class "B" includes "A"
The class "C" includes "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;
}
};
这样,一切正常,输出:
Hello from A Hello from B Hello from C
但是,如果我这样做:
#include <iostream>
#include <a.hpp>
#include <vector>
class B
{
public:
B()
{
std::cout << "Hello from B" << std::endl;
}
private:
std::vector<A> garage;
};
我遇到了一系列错误,包括这个错误(实际上是主要错误,因为那个错误,还有其他错误):
error: 'A' was not declared in this scope
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;
}
主要.cpp
#include <iostream>
#include <A.hpp>
int main(int argc, char ** argv)
{
A a;
return 0;
}
海湾合作委员会
g++ -O2 -std=c++11 -I"." -o exchange A.cpp B.cpp C.cpp main.cpp
输出
In file included from ./A.hpp:5:0,
from ./C.hpp:5, from C.cpp:1:
./B.hpp:13:17: error: 'A' was not declared in this scope
std::vector<A> garage;
最佳答案
将类定义与类成员定义分开:
#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;
}
在较大的项目中,您可能会为其中的每一个都有单独的头文件和源文件。
关于c++ - "Exchange"包括,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21867489/