简体   繁体   English

C ++构造函数基于参数类型调用另一个构造函数

[英]C++ constructor call another constructor based on parameter type

I have this class 我有这门课

class XXX {
    public:
        XXX(struct yyy);
        XXX(std::string);
    private:
        struct xxx data;
};

The first constructor (who works with a structure) is easy to implement. 第一个构造函数(使用结构)很容易实现。 The second I can parte one string in a specific format, parse and I can extract the same structure. 第二个我可以以特定格式分开一个字符串,解析并且我可以提取相同的结构。

My question is, in java I can do something like this: 我的问题是,在java中我可以这样做:

XXX::XXX(std::string str) {

   struct yyy data;
   // do stuff with string and extract data
   this(data);
}

Using this(params) to call another constructor. 使用this(params)来调用另一个构造函数。 In this case I can something similar? 在这种情况下,我可以类似的东西?

Thanks 谢谢

The term you're looking for is " constructor delegation " (or more generally, " chained constructors "). 您正在寻找的术语是“ 构造函数委托 ”(或更一般地说,“ 链式构造函数 ”)。 Prior to C++11, these didn't exist in C++. 在C ++ 11之前,这些在C ++中不存在。 But the syntax is just like invoking a base-class constructor: 但语法就像调用基类构造函数一样:

class Foo {
public:
    Foo(int x) : Foo() {
        /* Specific construction goes here */
    }
    Foo(string x) : Foo() {
        /* Specific construction goes here */
    }
private:
    Foo() { /* Common construction goes here */ }
};

If you're not using C++11, the best you can do is define a private helper function to deal with the stuff common to all constructors (although this is annoying for stuff that you'd like to put in the initialization list). 如果您没有使用C ++ 11,那么您可以做的最好的事情是定义一个私有帮助函数来处理所有构造函数共有的东西(虽然这对于您想要放在初始化列表中的东西很烦人) 。 For example: 例如:

class Foo {
public:
    Foo(int x) {
        /* Specific construction goes here */
        ctor_helper();
    }
    Foo(string x) {
        /* Specific construction goes here */
        ctor_helper();
    }
private:
    void ctor_helper() { /* Common "construction" goes here */ }
};

Yes. 是。 In C++11, you can do that. 在C ++ 11中,您可以这样做。 It is called constructor delegation . 它被称为构造函数委托

struct A
{
   A(int a) { /* code */ }

   A() : A(100)  //delegate to the other constructor
   {
   }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM