未初始化的局部变量使用 C++
uninitialized local variable used c++
为什么我不能用 Strct
结构的 number
字段的值初始化整型变量 num
?
#include <iostream>
struct Strct
{
float number = 16.0f;
};
int main()
{
Strct* strct;
int num = strct->number;
return 0;
}
Error List: C4700 uninitialized local variable 'strct' used
Why can't I initialize the integer variable num with the value of the number field of the Strct structure?
因为指针未初始化,因此它不指向任何对象。通过指针进行间接访问,甚至读取指针的值都会导致未定义的行为。
I thought my strct points to the Strct structure, that is, to its type
没有。指针不指向类型。对象指针指向对象。类型不是 C++ 中的对象。
16.0f 不是 number
的值。 16.0f 是该成员的默认成员初始化程序。如果您创建类型为 Strct
的对象,并且没有为该成员提供初始化程序,则默认成员初始化程序将用于初始化相关对象的成员。
then can I define a member function that returns the address of this structure?
结构是一种类型。类型不存储在地址中。没有“类型地址”之类的东西。
这里是一个如何创建变量来命名 class Strct
实例的示例:
Strct strct;
您可以使用成员访问运算符访问此变量的成员:
int num = strct.number;
这是一个如何创建不使用默认成员初始化程序的实例的示例:
Strct strct = {
.number = 4.2f,
};
为什么我不能用 Strct
结构的 number
字段的值初始化整型变量 num
?
#include <iostream>
struct Strct
{
float number = 16.0f;
};
int main()
{
Strct* strct;
int num = strct->number;
return 0;
}
Error List: C4700 uninitialized local variable 'strct' used
Why can't I initialize the integer variable num with the value of the number field of the Strct structure?
因为指针未初始化,因此它不指向任何对象。通过指针进行间接访问,甚至读取指针的值都会导致未定义的行为。
I thought my strct points to the Strct structure, that is, to its type
没有。指针不指向类型。对象指针指向对象。类型不是 C++ 中的对象。
16.0f 不是 number
的值。 16.0f 是该成员的默认成员初始化程序。如果您创建类型为 Strct
的对象,并且没有为该成员提供初始化程序,则默认成员初始化程序将用于初始化相关对象的成员。
then can I define a member function that returns the address of this structure?
结构是一种类型。类型不存储在地址中。没有“类型地址”之类的东西。
这里是一个如何创建变量来命名 class Strct
实例的示例:
Strct strct;
您可以使用成员访问运算符访问此变量的成员:
int num = strct.number;
这是一个如何创建不使用默认成员初始化程序的实例的示例:
Strct strct = {
.number = 4.2f,
};