我正在学习C,我读到所有引用必须在声明时初始化,
并且不会有“未初始化的引用”.但是如果引用变量是一个类成员呢?
并且不会有“未初始化的引用”.但是如果引用变量是一个类成员呢?
class test { int &k; }; int main() { test *abc = new test; }@H_301_5@该程序编译并正常运行(g,无警告).但是,abc-> k是一个引用,但是它被初始化为什么?或者,这是某种“未初始化的参考”,还是其他的?
解决方法
该程序是不正确的,因为它构造一个类不能初始化引用类型的非静态成员实体.
@H_301_5@我相信gcc不能编译这个,但是我只收到在类中没有构造函数的“非静态引用”int& test :: k’的警告.
@H_301_5@test是一个非POD-struct类型,因为它包含一个引用成员. (9 [class] / 4)
@H_301_5@new test default – 初始化动态分配的类. (5.3.4 [expr.new] / 15)
@H_301_5@默认初始化类型test的对象意味着调用隐式声明和隐式定义的默认构造函数. (8.5 [dcl.init] / 5)
@H_301_5@隐式定义的默认构造函数等同于具有空mem-initialized-list和空函数体的默认构造函数. (12.1 [class.ctor] / 7)
@H_301_5@更多:
@H_301_5@The implicitly-defined default constructor performs the set of initializations of the@H_301_5@如果实体在mem-initializer-list中不是名称,并且成员不是类型[具有进一步限制],则实体未初始化.
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.
@H_301_5@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)