微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 类定义中的引用变量

我正在学习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)

原文地址:https://www.jb51.cc/c/113508.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐