C++ 使用另一个类的 typedef'ed 成员时出现编译错误

C++ Compilation error when using typedef'ed members of another class

本文关键字:成员 ed 错误 编译 另一个 typedef C++      更新时间:2023-10-16

以下代码有什么问题。我收到编译错误。我也尝试过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>,你会没事的。


有关详细信息,请阅读:何时可以使用前向声明?

代码中的问题是 B::BPtr 没有在类 A 声明之前声明。您应该在使用前声明BPtr。例如:

class B;
class A;
typedef std::shared_ptr<B> BPtr;
typedef std::shared_ptr<A> APtr;

class A
{
public: 
    APtr get_a_ptr();    
    BPtr get_b_ptr();
};
class B
{
public:    
    BPtr get_b_ptr();
    APtr get_a_ptr();
};

请记住,在完整类声明之前,不能将operator*operator->shared_ptr一起使用。