可以在c ++中构造函数调用另一个构造函数? [英] Can constructor call another constructor in c++?

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

问题描述

class A{
  A(int a = 5){
    DoSomething();
    A();
  }
  A(){...}
}

第一个构造函数是否可以调用第二个构造函数?

Can the first constructor call the second one?

推荐答案

不要之前的C ++ 11

将公共功能提取到单独的函数中。我通常命名这个函数 construct()

Extract the common functionality into a separate function instead. I usually name this function construct().

所谓的第二个调用将编译,但在C ++中有不同的含义:它会构造一个新的对象,一个临时的,然后立即在语句结束时删除。所以,不是。

The "so-called" second call would compile, but has a different meaning in C++: it would construct a new object, a temporary, which will then be instantly deleted at the end of the statement. So, no.

但是,析构函数可以毫无问题地调用。

A destructor, however, can be called without a problem.

这篇关于可以在c ++中构造函数调用另一个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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