我是从C++之旅中读到的,
"Unlike an ordinary function, a constructor is guaranteed to be used to initialize objects of its class. Thus, defining a constructor eliminates the problem of uninitialized variables for a class."
初始化如何进行?例如,假设我有一个类别为
string
的字段“s”的类class C{
std::string s;
...
}
如何初始化“s”,并且无论编译器如何,其值都可以保证为空字符串?
最佳答案
制作完C
实例后,将在称为Member initialization的情况下初始化std::string s
。
How does "s" get initialized, and would its value be guaranteed to be the empty string whatever the compiler?
您没有向我们展示如何创建
C
,所以我们不知道使用了什么构造函数。如果使用默认构造函数,则将std::string
的默认构造函数用于s
。确实确实产生了一个空字符串,如here所述:Default constructor. Constructs empty string (zero size and unspecified capacity).
关于c++ - C++构造函数如何初始化其类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214568/