未调用C ++构造函数 [英] C++ constructor not called

查看:86
本文介绍了未调用C ++构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,当Car()执行时,构造函数仅被调用一次(即)。为什么在语句Car o1(Car())上不第二次调用?

In the following code the constructor is called only once (i.e.) when Car() executes. Why is it not called the second time on the statement Car o1(Car())?

#include <stdio.h>
#include <iostream>

class Car
{
public :
   Car()
   {
      std::cout << "Constructor" << '\n';
   }
   Car(Car &obj)
   {
      std::cout << "Copy constructor" << '\n';
   }
};

int main()
{
   Car();
   Car o1(Car()); // not calling any constructor
   return 0;
}


推荐答案

Car o1(Car());

这将声明一个名为 o1 的函数 Car 并接受一个参数,该参数是返回 Car 的函数。这就是最烦人的分析

This declares a function called o1 that returns a Car and takes a single argument which is a function returning a Car. This is known as the most-vexing parse.

您可以通过使用额外的一对括号来修正它:

You can fix it by using an extra pair of parentheses:

Car o1((Car()));

或者通过在C ++ 11及更高版本中使用统一初始化:

Or by using uniform initialisation in C++11 and beyond:

Car o1{Car{}};

但是要使此功能起作用,您需要将 Car 构造函数一个 const Car& ,否则您将无法将临时绑定到它。

But for this to work, you'll need to make the parameter type of the Car constructor a const Car&, otherwise you won't be able to bind the temporary to it.

这篇关于未调用C ++构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆