加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 类定义中的引用变量

发布时间:2020-12-16 05:52:35 所属栏目:百科 来源:网络整理
导读:我正在学习C,我读到所有引用必须在声明时初始化, 并且不会有“未初始化的引用”.但是如果引用变量是一个类成员呢? class test{ int k;};int main(){ test *abc = new test;} 该程序编译并正常运行(g,无警告).但是,abc- k是一个引用,但是它被初始化为什么?
我正在学习C,我读到所有引用必须在声明时初始化,
并且不会有“未初始化的引用”.但是如果引用变量是一个类成员呢?
class test
{
    int &k;
};

int main()
{
    test *abc = new test;
}

该程序编译并正常运行(g,无警告).但是,abc-> k是一个引用,但是它被初始化为什么?或者,这是某种“未初始化的参考”,还是其他的?

解决方法

该程序是不正确的,因为它构造一个类不能初始化引用类型的非静态成员实体.

我相信gcc不能编译这个,但是我只收到在类中没有构造函数的“非静态引用”int& test :: k’的警告.

test是一个非POD-struct类型,因为它包含一个引用成员. (9 [class] / 4)

new test default – 初始化动态分配的类. (5.3.4 [expr.new] / 15)

默认初始化类型test的对象意味着调用隐式声明和隐式定义的默认构造函数. (8.5 [dcl.init] / 5)

隐式定义的默认构造函数等同于具有空mem-initialized-list和空函数体的默认构造函数. (12.1 [class.ctor] / 7)

更多:

The implicitly-defined default constructor performs the set of initializations of the
class that would be performed by a user-written default constructor for that class with an empty mem-initializer-list (12.6.2) and an empty function body. If that user-written default constructor would be ill-formed,the program is ill-formed.

如果实体在mem-initializer-list中不是名称,并且成员不是类型[具有进一步限制],则实体未初始化.

Otherwise,the entity is not initialized. If the entity is of const-qualified type,or reference type,[or …] the program is ill-formed.” (12.6.2 [class.base.init] / 4)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读