如何从另一个构造函数调用 C++ 类构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39199023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:49:32  来源:igfitidea点击:

How to call a C++ class Constructor from another Constructor

c++objectmethodsconstructoroverloading

提问by WoodMath

I'm trying to create an object in C++ that requires multiple object constructors. Say Foo()and Foo(int)where Foo(int)then calls Foo(). The simplified code is written below:

我正在尝试用 C++ 创建一个需要多个对象构造函数的对象。说Foo()然后Foo(int)在哪里Foo(int)打电话Foo()。简化后的代码如下:

#include <iostream>
class Foo{

private:
        int iX; 

public:
        void printX(string sLabel){
            cout << sLabel << " : " << " Foo::iX = " << Foo::iX << endl;
        };  
        void setX(int iX){
            Foo::iX = iX; 
            Foo::printX("setX(void) Method");
        };  
        Foo(){
            Foo::iX = 1;
            Foo::printX("Foo(void) Constructor");
        };
        Foo(int iX){
            Foo::setX(iX);
            Foo::printX("Foo(int) Constructor");
            Foo::Foo();
            Foo::printX("Foo(int) Constructor");

        };  
};

int main( int argc, char** argv ){

    Foo bar(2);

    return 0;
}

The output of which is

其中的输出是

setX(void) Method :  Foo::iX = 2
Foo(int) Constructor :  Foo::iX = 2
Foo(void) Constructor :  Foo::iX = 1
Foo(int) Constructor :  Foo::iX = 2

As the results indicate setXmethod works as expected. Foo::iXis equal to 2inside and outside of scope of that function.

结果表明setX方法按预期工作。Foo::iX等于2该函数的范围内外。

However when calling the Foo(void)constructor from within the Foo(int)constructor, Foo::iXstays equal to 1only within that constructor. As soon as it exits out that method, it reverts back to 2.

但是,当Foo(void)Foo(int)构造函数中调用构造函数时,仅在该构造函数中Foo::iX保持等于1。一旦退出该方法,它就会恢复到2.

So my question is 2-fold:

所以我的问题是两方面的:

  1. Why does C++ behave this (a constructor cannot be called from within another constructor without values that were assigned)?
  2. How can you create multiple constructor signatures, but without redundant duplicate code doing the same thing?
  1. 为什么 C++ 会这样(一个构造函数不能在没有赋值的情况下从另一个构造函数中调用)?
  2. 如何创建多个构造函数签名,但没有多余的重复代码做同样的事情?

回答by songyuanyao

Foo::Foo();in Foo::Foo(int)is not invoking the default constructor on the current object as you expected. It just constructs a temporary Foo, which has nothing to with the current object.

Foo::Foo();inFoo::Foo(int)没有按预期调用当前对象的默认构造函数。它只是构造一个临时的Foo,与当前对象无关。

You can use delegating constructor(since C++11) like this:

您可以像这样使用委托构造函数(C++11 起):

Foo(int iX) : Foo() {
    // ...
}; 

Note that Foo::Foo()will be invoked in advance of the body of Foo::Foo(int)here.

请注意,Foo::Foo()将在Foo::Foo(int)此处的主体之前调用。

An alternative to avoid duplicated code is to use setX()as a common initialization method. (Or make a new one if not appropriate.)

避免重复代码的另一种方法是setX()用作通用初始化方法。(如果不合适,或者制作一个新的。)

Foo() {
    setX(1);
    // ...
};
Foo(int iX) {
    setX(iX);
    // ...
}; 

回答by R Sahu

If you are able to use a C++11 compiler, you can use delegating constructors.

如果您能够使用 C++11 编译器,则可以使用委托构造函数。

// Use Foo(int) to initialize the object when default constructor is used.
Foo() : Foo(1) {}

回答by Wiki Wang

A constructor CAN be called from within another constructor. You just forget to assign the return value.

可以从另一个构造函数中调用构造函数。您只是忘记分配返回值。

*this = Foo::Foo();

For question 2, you need delegating constructors.

对于问题 2,您需要委托构造函数

Foo(int iX) : Foo() {
    ...
}