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

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

问题描述

作为 C#开发人员,我习惯于通过构造函数运行: / p>



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

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

public Test(整数计数,字符串名称):this(count){
DoSomethingWithName(name);
}
}

是否可以用C ++做到这一点? / p>

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

解决方案

C ++ 11:是的!



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



语法与C#稍有不同:

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

C ++ 03:否



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


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

      class Foo {
    public :
    Foo(char x,int y = 0); //合并两个构造函数(char)和(char,int)
    // ...
    };


  2. 使用初始化方法共享通用代码:

      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)
    {
    // ...
    }


请参见 C ++ FAQ条目供参考。


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

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++?

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

解决方案

C++11: Yes!

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

The syntax is slightly different from C#:

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

C++03: No

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

  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:

    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 ++中从另一个构造函数调用构造函数(构造函数链接)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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