Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

c++ - 我可以在C ++中从另一个构造函数调用构造函数(进行构造函数链接)吗?(Can I call a constructor from another constructor (do constructor chaining) in C++?)

As a C# developer I'm used to run through constructors:

(作为C#开发人员,我习惯于遍历构造函数:)

class Test {
    public Test() {
        DoSomething();
    }

    public Test(int count) : this() {
        DoSomethingWithCount(count);
    }

    public Test(int count, string name) : this(count) {
        DoSomethingWithName(name);
    }
}

Is there a way to do this in C++?

(有没有办法在C ++中做到这一点?)

I tried calling the Class name and using the 'this' keyword, but both fails.

(我尝试调用类名称并使用'this'关键字,但均失败。)

  ask by Stormenet translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C++11: Yes!

(C ++ 11:是的!)

C++11 and onwards has this same feature (called delegating constructors ).

(C ++ 11及更高版本具有相同的功能(称为委托构造器 )。)

The syntax is slightly different from C#:

(语法与C#略有不同:)

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {}
};

C++03: No

(C ++ 03:否)

Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:

(不幸的是,在C ++ 03中没有做到这一点的方法,但是有两种模拟方法:)

  1. You can combine two (or more) constructors via default parameters:

    (您可以通过默认参数组合两个(或多个)构造函数:)

     class Foo { public: Foo(char x, int y=0); // combines two constructors (char) and (char, int) // ... }; 
  2. Use an init method to share common code:

    (使用init方法共享通用代码:)

     class Foo { public: Foo(char x); Foo(char x, int y); // ... private: void init(char x, int y); }; Foo::Foo(char x) { init(x, int(x) + 7); // ... } Foo::Foo(char x, int y) { init(x, y); // ... } void Foo::init(char x, int y) { // ... } 

See the C++FAQ entry for reference.

(请参阅C ++ FAQ条目以供参考。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...