如何执行参数化构造函数的调用?
How the invoking of parameterized constructor is executed?
有一段代码具有友元函数和运算符重载,我得到的输出部分有意义,所以这是代码,我没有得到的是,当调用 are 中使用对象参数时,如何调用具有浮点类型参数的构造函数。
class a
{
public:
a():n(3),d(2)
{
cout<<endl<<"default constructor called";
}
a(float f):n(f),d(1)
{
cout<<endl<<"type casting constructor called";
}
a(const a &f)
{
cout<<endl<<"copy constructor called";
}
friend a operator+( a x, a y);
};
a operator+(a x, a y)
{
return x;
}
还有主要部分
int main()
{
a f1;
float f=1.5;
f1+f;
}
问题恰恰是如何调用参数化构造函数或类型转换构造器?
Output:
default constructor called
type casting constructor called
copy constructor called
copy constructor called
...
如果我做对了,你想知道为什么当你向a
的现有实例添加float
时会调用a(float f)
构造函数。
因此,这是由隐式构造引起的,并且由于以下几件事而发生:
- 您有一个将
float
作为参数的构造函数。 - 您有一个
operator+
重载,它需要两个a
实例。
因此,当您执行加法时,右侧变量是一个float
。由于您可以使用浮点数实例化a
,因此调用构造函数来创建a
实例以将其添加到左侧实例。然后,您将获得两个副本,因为operator+
函数通过复制获取两个a
实例。
分步细分如下:
a f1; // Outputs "default constructor called"
f1 + f; // "f" is a float, so we can construct an instance of "a".
f1 + a(f); // Outputs "type casting constructor called"
operator+(a x, a y); // Takes two copies, so outputs "copy constructor called" twice
既然我解释了正在发生的事情,我想我也应该解释如何避免它。
无论出于何种原因,如果您不希望发生隐式构造,则可以执行以下两项操作之一:
- 在采用
float
参数的构造函数前面加上explicit
关键字,这意味着构造函数永远不会作为隐式转换或复制初始化的一部分进行调用。它也将不再允许您将任何可以转换为float
的参数隐式传递给它。 - 声明并定义另一个将
float
作为其右侧参数的operator+
函数。像friend a operator+(a x, float y)
.将调用此运算符而不是当前运算符,因为它不需要转换即可工作。
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 减少复制构造函数调用
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 在 Google 测试中,我可以从构造函数调用 GetParam() 吗?
- C++ - 从另一个类构造函数调用类构造函数
- 在C++中初始化带有和不使用构造函数调用的对象有什么区别
- 是否可以从移动构造函数调用默认构造函数?
- 在模板生成器模式中分解重复的构造函数调用
- std::atexit 从全局对象的构造函数调用时的排序
- 对构造函数调用的约束
- 编译器错过了无效的构造函数调用,并调用不存在的(或私有的)默认构造函数
- 用构造函数调用填充向量
- 创建指针时是否没有构造函数调用
- 使用 emplace_back 避免移动构造函数调用的最佳方法?
- C++ 抽象类构造函数调用
- 为什么函数参数将带有参数的构造函数调用
- 为什么比“构造函数”调用更多的“解构器”调用
- 将对象传递给函数并不是导致构造函数调用