Holder class (Having some objects references) compile error: 'Can not be referenced -- it is a deletted funciton'

Holder class (Having some objects references) compile error: 'Can not be referenced -- it is a deletted funciton'

我需要一个“持有人”class。它应该存储对象引用。

喜欢:holder.A =一个; // 获取引用!

下面的示例代码包括编译器错误:

class A
{
};

class Holder
{
public:
    A& MyA; // I want to store a reference.
};

int main()
{
    A testA;
    Holder holder; // Compiler error: the default constructor of "Holder" cannot be referenced -- it is a deleted function
    holder.A = testA; // I was hopping to get testA reference.
}

问题是因为你的classHolder有一个引用数据成员MyA,它的默认构造函数Holder::Holder()将被隐式删除。

这可以从Deleted implicitly-declared default constructor看出:

The implicitly-declared or defaulted (since C++11) default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true:

  • T has a member of reference type without a default initializer (since C++11).

(强调我的)


为了解决这个你可以提供一个构造函数来初始化引用数据成员MyA如下所示:

class A
{
};

class Holder
{
public:
    A& MyA; 
    //provide constructor that initialize the MyA in the constructor initializer list
    Holder( A& a): MyA(a)//added this ctor
    {
        
    }
};

int main()
{
    A testA;
    Holder holder(testA); //pass testA
    
}

Working Demo

引用 (MyA) 应该绑定到某物并且不能为空,因为你没有告诉它应该绑定到什么,默认构造函数是错误的。

prog.cc: In function 'int main()': prog.cc:23:12: error: use of deleted function 'Holder::Holder()' 23 | Holder holder; // Compiler error: the default constructor of "Holder" cannot be referenced -- it is a deleted function | ^~~~~~ prog.cc:14:7: note: 'Holder::Holder()' is implicitly deleted because the default definition would be ill-formed: 14 | class Holder

您需要添加一个构造函数指定如何初始化MyA

Holder(A &obj):MyA(obj){}

然后创建 holder 对象

A testA;
Holder holder(testA);