【问题标题】:Constructor of struct calling the member function of another class declared as a pointerstruct 的构造函数调用另一个声明为指针的类的成员函数
【发布时间】:2022-08-09 22:13:39
【问题描述】:

我有以下代码:

class Cohomology;

struct EMField
{
     std::unique_ptr<Cohomology> coh;
     std::array<DIM> data;

     EMField() {coh -> initializeField(*this);};
}

class Cohomology
{
     private:
        // private members
     public:
        Cohomology(PList params)
        {
             // Constructor of the class
        }

        void initializeField(EMField& field)
        {
             field.coh.reset(this);
             // other methods to initialize field.data using the private members
        }
}

In this answer 解释了调用不完整类型的方法是不可能的,也不能取消引用指针。

事实上,当我尝试编译它时,我得到:

warning: invalid use of incomplete type ‘class Cohomology‘

note: forward declaration of ‘class Cohomology‘

我的问题是:如果我不能使用std::unique_ptr&lt;Cohomology&gt; coh 的成员,我如何将EMField 的构造委托给Cohomology 类?

    标签: c++


    【解决方案1】:

    只需移动EMField::EMField() 的定义,直到两个类都定义完毕。

    类上同调;

    struct EMField
    {
         std::unique_ptr<Cohomology> coh;
         std::array<DIM> data;
    
         EMField();
    }
    
    class Cohomology
    {
         private:
            // private members
         public:
            Cohomology(PList params)
            {
                 // Constructor of the class
            }
    
            void initializeField(EMField& field)
            {
                 field.coh.reset(this);
                 // other methods to initialize field.data using the private members
            }
    }
    
    inline EMField::EMField()
    {
        coh -> initializeField(*this);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多