【问题标题】:How the invoking of parameterized constructor is executed?参数化构造函数的调用是如何执行的?
【发布时间】:2020-03-20 04:16:46
【问题描述】:

这段代码有友元函数和运算符重载,我得到的输出部分有意义,所以这是代码,我没有得到的是构造函数如何具有当在 中进行的调用带有对象参数时,将调用浮点类型参数。

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

...

【问题讨论】:

  • 将浮点构造函数标记为显式,然后看看会发生什么
  • 代码无法编译,因为没有nd 的声明。

标签: c++ operator-overloading copy-constructor default-constructor friend-function


【解决方案1】:

如果我猜对了,您会想知道为什么当您将 float 添加到 a 的现有实例时会调用 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

既然我解释了发生了什么,我想我也应该解释一下如何避免它。

如果出于某种原因,您希望隐式构造发生,您可以做以下两件事之一:

  • 使用explicit 关键字为接受float 参数的构造函数添加前缀,这意味着构造函数永远不会作为隐式转换或复制初始化的一部分被调用。它也将不再允许您将任何可以转换为 float 的参数隐式传递给它。
  • 声明并定义另一个operator+ 函数,该函数将float 作为其右侧参数。像friend a operator+(a x, float y) 这样的东西。将调用此运算符而不是当前运算符,因为它不需要转换即可工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 2013-03-05
    • 1970-01-01
    • 2021-08-31
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多