【问题标题】:What is the correct way for me to access a public member of class A in class B when class B is a member of class A in C++?当 B 类是 C++ 中 A 类的成员时,我访问 B 类中 A 类的公共成员的正确方法是什么?
【发布时间】:2018-08-09 17:43:44
【问题描述】:

在下面的示例中,我希望能够在函数ShareData 中访问类B 中的向量cList。我该怎么做?

我已经编写了一个示例代码。它无法编译(错误消息:B 没有构造函数)。即使确实如此,cObj = new B(*this); 行是否会引入任何循环依赖?

#include "stdafx.h"
#include <vector>

class B;

class A
{
public:
    B* cObj;
    std::vector<B*> cList;
    A()
    {
        cObj = new B(*this);
    }
};

class B
{
public:
    B(A& aObj) : aObjLocal(aObj) {};
    void ShareData(int result)
    {
        for (auto& iterator : aObjLocal.cList)
        {
            (*iterator).ShareData(result);
        }
    }
private:
    A& aObjLocal;
};


void main()
{
    A aMain;
    B bMain(aMain);
    bMain.ShareData(10);
}

提前感谢您分享知识。

【问题讨论】:

    标签: c++ class pointers function-pointers


    【解决方案1】:

    当您使用前向声明时,您需要确保需要完整类型的前向声明类型的任何使用发生在类型完全定义之后。

    在您的情况下,这意味着您的代码应如下所示:

    class B;
    
    class A
    {
    public:
        B* cObj;
        std::vector<B*> cList;
        A();
    };
    
    class B {
       ...
    };
    
    inline A::A()
    {
        cObj = new B(*this);
    }
    

    此外,在这样做的同时,您当然希望摆脱拥有 B*,而在此处使用 std::unique_ptr

    【讨论】:

      【解决方案2】:

      线

          cObj = new B(*this);
      

      A 的构造函数中不起作用,因为B 的定义在该行不可见。在定义B之后移动A的构造函数的实现。

      class A { ... };
      
      class B { ... };
      
      inline A::A()
      {
          cObj = new B(*this);
      }
      

      【讨论】:

      • 这样做会导致错误:“'A::A': cannot define a compiler-generated special member function (必须先在类中声明)”
      • @JayHawk,你必须在类中声明构造函数。 A();。你只是无法定义它。
      • 太棒了!谢谢。
      • 如果头文件和方法的实现,包括构造函数在不同的文件中,会有什么风险吗?
      • @JayHawk,你说的是“分离 .h 文件”还是“分离 .h 文件和 .cpp 文件”?
      【解决方案3】:

      cObj = new B(*this);
      您不能在此处使用 B,因为它尚未定义。 把它放在B的定义下:

      A::A()
      {
          cObj = new B(*this);
      }
      

      并删除内联定义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-01
        • 2014-09-23
        • 1970-01-01
        • 2017-03-14
        • 2021-03-01
        相关资源
        最近更新 更多