【问题标题】:C++ Compilation error when using typedef'ed members of another class使用另一个类的 typedef 成员时 C++ 编译错误
【发布时间】:2016-05-21 14:48:08
【问题描述】:

以下代码有什么问题。 我收到编译错误。 我也尝试过 B 类的前向声明。但未能成功。

Test.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;
}

【问题讨论】:

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


    【解决方案1】:

    这样做:

    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&lt;B&gt;,你会没事的。


    更多信息,请阅读:When can I use a forward declaration?

    【讨论】:

    • 但是为什么我不能在 A 类中使用 B 类的 shared_ptr 的 typedef 呢?
    • 我刚刚用该评论@aditya1811 的答案更新了我的答案。因为前向声明表明类B 将紧随其后,所以我向编译器先生保证,但编译器不知道B 里面会有什么类。
    【解决方案2】:

    您的代码中的问题是 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-&gt;shared_ptr 一起使用。

    【讨论】:

    • 当然这也是一个解决方案。应该已经涵盖了,太棒了!
    • 我不喜欢 shared_ptr 的 typedef,所以在实践中我选择了你的答案 (=
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多