在 C++ 中,默认情况下构造函数为类的数据成员提供的值是多少?

what is the value given to data members of the class by default constructor in c++?

本文关键字:数据成员 多少 C++ 默认 情况下 构造函数      更新时间:2023-10-16

就像在 Java 中构造函数给出的默认值是 0,我在某处听说在 C++ 中构造函数没有给出默认值,但后来我做了一个简单的程序并打印数据成员的值,它打印 0 所以?

#include<iostream>
class testclass
{ int value1;
int value2;
public :
void print(){
std::cout<<value1<<value2;
} 
};
int  main(){
testclass t1;
t1.print();
return 0 ;
}

上面的代码打印 0 作为输出,所以...?

我在某处听说在 C++ 中默认值不是由构造函数给出的,但后来我做了一个简单的程序并打印数据成员的值,它打印 0 所以?

一些编译器可能会这样做,但根据标准,使用这些成员变量会导致未定义的行为。

不要指望他们。确保成员变量已正确初始化。

class testclass
{
int value1 = 0;
int value2 = 0;
...
};

class testclass
{
int value1;
int value2;
public:
testclass() : value1(0), value2(0) {}
...
};