如何执行参数化构造函数的调用?



有一段代码具有友元函数和运算符重载,我得到的输出部分有意义,所以这是代码,我没有得到的是,当调用 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)构造函数。

因此,这是由隐式构造引起的,并且由于以下几件事而发生:

  1. 您有一个将float作为参数的构造函数。
  2. 您有一个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).将调用此运算符而不是当前运算符,因为它不需要转换即可工作。

最新更新