没有参数的默认构造函数是否总是初始化变量?

Will a Default Constructor With no Parameters Always Initialize Variables?

本文关键字:初始化 变量 是否 构造函数 参数 默认      更新时间:2023-10-16

我有一个类,其中包含一个默认构造函数,该构造函数应该初始化几个私有成员变量。我想知道我的变量是否被初始化过,因为当我调用 variables_in_class 方法时,不会打印任何内容。有人可以向我解释一下吗?我的代码如下:

class Practice_Class
{
public:
Practice_Class()
{
a = 6;
b = 89;
c = 45;
}
void variables_in_class()
{
cout << a << " "<< b << " "<< c << " "<< endl;
}
private:
int a, b, c;
};

int main()
{
Practice_Class the_value;
cout << the_value.variables_in_class();
}

这应该有效:

int main()
{
Practice_Class the_value;
// you are outputing in variables_in_class(), not its return values
the_value.variables_in_class();
}

对于您的问题:

没有参数的默认构造函数是否总是初始化变量?

不。如果在默认构造函数中不执行任何操作,它将自动调用类成员的默认构造函数。除此之外,它什么也没做。

我有一个包含默认构造函数的类,该构造函数应该 初始化几个私有成员变量。

您不初始化您的。你分配它们。以下是使用初始化列表执行此操作的正确方法:

Practice_Class() :
a(6),
b(89),
c(45)
{
}

我想知道我的变量是否被初始化过,因为当我调用 variables_in_class 方法时,不会打印任何内容。

代码甚至不应该编译。见下文:

cout << the_value.variables_in_class();

variables_in_class()是一个void函数(而且名称很差)。它不返回任何内容。它在内部使用流的事实在调用站点上无关紧要。不能将不存在的函数结果传递给std::cout。只需调用该函数:

the_value.variables_in_class();

尽管如此,惯用C++方法是为类提供相应的输出流重载,以便可以将类的实例传递给std::cout或其他输出流。

例:

#include <iostream>
class Practice_Class
{
public:
Practice_Class() :
a(6),
b(89),
c(45)
{
}
private:
// so that the function below can access the variables:
friend std::ostream& operator<<(std::ostream& os, Practice_Class const& obj);
int a;
int b;
int c;
};
std::ostream& operator<<(std::ostream& os, Practice_Class const& obj)
{
os << obj.a << " " << obj.b << " " << obj.c;
return os;
}
int main()
{
Practice_Class the_value;
std::cout << the_value << 'n';
}