C++初始化类实例时隐式调用类成员的构造函数
C++ implicitly calling class member's constructor when initializing the class instance
我还在学习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 )
. 有些人认为这是大多数单参数构造函数的良好做法。
相关文章:
- 无法调用成员函数,尝试正确执行此操作仍然失败
- 在 transform() 中调用成员函数
- C++::在构造函数退出之前通过指针调用成员函数
- 为什么我可以通过野生指针调用成员函数
- 从 Qt 中的信号调用成员函数的问题
- 调用C++成员函数指针,而不知道哪个类
- 如何从嵌套在命名空间中的类调用成员函数?
- 无法在非成员函数中调用成员函数
- 为什么分配了 nullptr 的指针可以调用成员函数?
- 通过带有成员函数指针的 QHash 调用成员函数的正确方法
- 使用可变参数模板调用成员函数
- 调用成员对象的构造函数
- 有没有办法在没有括号的情况下在C++中调用成员的getter/setter?
- 如何调用成员初始化器列表中参考成员的构造函数
- 使用按引用调用时,不能在没有对象的情况下调用成员函数 const
- 如果绝对没有调用成员函数,是否允许使用不完整类型的向量?如果是这样,从什么时候开始
- 在另一个成员函数中调用成员函数时'int'之前的预期主表达式
- 为什么调用成员函数不调用该对象的 ODR-USE?
- 如何在模板参数中调用成员
- 是否可以使用 EXPECT_CALL 来验证模拟对象的构造函数是否在某些时候调用成员函数?