下面的代码有什么问题。 我收到编译错误。 我也尝试过B类的前向声明。但没有成功。
测试.cpp
#include <memory>
#include <iostream>
namespace api
{
class A
{
public:
typedef std::shared_ptr<A> APtr;
APtr get_a_ptr();
B::BPtr get_b_ptr();
};
class B
{
public:
typedef std::shared_ptr<B> BPtr;
BPtr get_b_ptr();
A::APtr get_a_ptr();
};
}
int main(int argc, char **argv)
{
return 0;
}
最佳答案
这样做:
namespace api
{
class B; // forward declaration
class A
{
public:
typedef std::shared_ptr<A> APtr;
APtr get_a_ptr();
std::shared_ptr<B> get_b_ptr();
};
...
}
问题是您正在向类 B
请求某些内容尚未定义。所以使用 std::shared_ptr<B>
你会没事的。
有关更多信息,请阅读:When can I use a forward declaration?
关于使用另一个类的 typedef 成员时出现 C++ 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364386/