没有参数的默认构造函数是否总是初始化变量?
Will a Default Constructor With no Parameters Always Initialize Variables?
我有一个类,其中包含一个默认构造函数,该构造函数应该初始化几个私有成员变量。我想知道我的变量是否被初始化过,因为当我调用 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';
}
相关文章:
- 初始值设定项列表是否只接受使用相同类型的值初始化变量?
- 在 C++ 中访问 lambda 捕获初始化变量
- 为什么C++不支持对未初始化变量进行智能分析?
- 使用 clang++ 和 g++ 在C++中初始化变量
- C++使用 lambda 初始化变量
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++ - 输出与初始化变量不同?
- C++/Win32 构造函数不使用从对话框获取的字符串初始化变量
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 具有静态存储持续时间的常量初始化变量的初始化顺序
- C++ 中的初始化变量
- C++中未初始化变量的值
- 如何在需要提及需要循环声明的其他类的类中初始化变量?
- 我想知道在构造函数中初始化变量时的生命周期
- 读取恰好具有良好值的未初始化变量
- 如何在 getter 的父类中初始化变量的情况下访问子类中的变量
- 为什么在 c++ 中有多种初始化变量的方法
- 没有参数的默认构造函数是否总是初始化变量?
- 是否可以使用 lambda 初始化变量(删除复制 ctor 时)
- 使用构造函数跳闸UB的新放置后使用初始化变量