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

标签 c++ class oop c++11 forward-declaration

下面的代码有什么问题。 我收到编译错误。 我也尝试过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/

相关文章:

python - Python中Enum和IntEnum之间的区别

ruby - 我的类名与 Ruby 的冲突

Python 默认/未命名方法

python - 嵌套构造函数。为什么需要它?

c++ - float 的二进制相等比较是否正确?

c++ - 根据窗口调整 QLabel 内 QPixmap 的大小

c++ - RegQueryValueEx 函数在 Windows7 上失败

php - 从 MYSQL 数据库填充 PHP 对象

java - Hibernate - 如何映射表示集合的对象

c++ - unique_ptr 列表的内容不可访问