类定义中的引用变量 [英] Reference variable in class definition
问题描述
我正在学习C ++,我读到所有引用必须在声明时初始化,
,并且没有未初始化的引用。但是如果引用变量是一个类成员怎么办?
class test
{
int& k ;
};
int main()
{
test * abc = new test;
}
此程序编译并正常运行(g ++,无警告)。然而, abc-> k
是一个引用,但是它初始化为什么?
程序是不成形的,因为它构造一个无法初始化引用类型的非静态成员实体的类。
我相信gcc不能编译这个,但我只收到警告non -static reference'int& test :: k'in class without a constructor。
test
-POD-struct类型,因为它包含引用成员。 (9 [class] / 4)
new test
默认初始化动态分配的类。 (5.3.4 [expr.new] / 15)
要默认初始化类型 / code>意味着调用隐式声明和隐式定义的默认构造函数。 (8.5 [dcl.init] / 5)
隐含定义的默认构造函数等价于一个带有空的默认构造函数mem- initialized-list 和一个空的函数体。 (12.1 [class.ctor] / 7)
更多:
隐式定义的默认构造函数执行
类的初始化集合,该集合将由用户编写的具有空的mem-initializer-list (12.6)的类的默认构造函数执行。 2)和一个空函数体。如果用户编写的默认构造函数是不成形的,那么程序就会失败。
$ b 否则,实体不被初始化。如果实体是const限定类型,或引用类型,[或...]程序是不成形的。(12.6.2 [class.base.init] / 4) I am learning C++, and I read that all references must be initialized upon declaration,
and there can be no "uninitialized references". But what if the reference variable is a class member? This program compiles and runs normally (in g++, no warnings). However, The program is ill-formed because it constructs a class that fails to initialize a non-static member entity of reference type. I believe that gcc should fail to compiler this, but I only received the warning "non-static reference ‘int& test::k’ in class without a constructor". To default-initialize an object of type The implicitly defined default constructor is equivalent to a default constructor with an empty mem-initialized-list and an empty function body. (12.1 [class.ctor] / 7) Further more: 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. If an entity is not name in a mem-initializer-list and the member is not of class type [with further restrictions] then the entity is not initialized. 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)
这篇关于类定义中的引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
class test
{
int &k;
};
int main()
{
test *abc = new test;
}
abc->k
is a reference, but what is it initialized to? Or, is it an "uninitialized reference" of some sort, or something else?test
is a non-POD-struct type as it contains a reference member. (9 [class] / 4)new test
default-initializes the dynamically allocated class. (5.3.4 [expr.new] / 15)test
means to call the implicitly declared and implicitly defined default constructor. (8.5 [dcl.init] / 5)