Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;使用typedef'时出现编译错误;教育其他班级的成员_C++_Class_Oop_C++11_Forward Declaration - Fatal编程技术网

C++ C++;使用typedef'时出现编译错误;教育其他班级的成员

C++ C++;使用typedef'时出现编译错误;教育其他班级的成员,c++,class,oop,c++11,forward-declaration,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:

以下代码有什么问题。 我得到编译错误。 我也试过提前申报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;
}
#包括
#包括
名称空间api
{
甲级
{
公众:
typedef std::共享\u ptr APtr;
APtr get_a_ptr();
B::BPtr get_B_ptr();
};
B类
{
公众:
typedef std::共享\u ptr BPtr;
BPtr get_b_ptr();
A::APtr get_A_ptr();
};
}
int main(int argc,字符**argv)
{
返回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();
  };
  ...
}
名称空间api
{
类B;//转发声明
甲级
{
公众:

typedef std::shared_ptr

代码中的问题是
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();
};
B类;
甲级;
typedef std::共享\u ptr BPtr;
typedef std::共享\u ptr APtr;
甲级
{
公众:
APtr get_a_ptr();
BPtr get_b_ptr();
};
B类
{
公众:
BPtr get_b_ptr();
APtr get_a_ptr();
};

请记住,在完整的类声明之前,您不能将
操作符*
操作符->
共享ptr
一起使用。

但是为什么我不能在类A中使用类B的共享ptr的typedef呢?我刚刚用注释@aditya1811的答案更新了我的答案。因为前向声明说类
B
已关闭我向编译器先生保证,我会遵守的,但编译器不可能知道里面会有什么类。当然,这也是一个解决方案。应该已经涵盖了这一点,太棒了!我不喜欢用typedefs来表示共享\u ptr,所以实际上我选择了你的答案(=