C++初始化类实例时隐式调用类成员的构造函数

C++ implicitly calling class member's constructor when initializing the class instance

本文关键字:调用 成员 构造函数 初始化 实例 C++      更新时间:2023-10-16

我还在学习C++之美。我今天遇到了一些代码,希望有人可以给我一些指导。 我有2节课

class B
{
public:
B( std::string s )
: m_string( s )
{
}
private:
std::string m_string;
};
class A
{
public:
A( B b )
: m_b( b )
{
}
private:
B m_b;
};

主.cpp

A a = A(std::string("hello"));

我对这样的初始化如何工作有点困惑?编译器如何知道std::string("hello)将传递给 B 的构造函数?

我试图找到相关文件,但没有运气。

当类具有采用单个参数的构造函数时,可以使用该构造函数将该参数隐式转换为该类的实例。 这意味着,只要需要B,您的B( std::string s )构造函数就允许传递字符串。

如果要禁止此隐式转换,请编写explicit B( std::string s ). 有些人认为这是大多数单参数构造函数的良好做法。