Can I call a constructor from another constructor (do constructor chaining) in C++?(我可以从 C++ 中的另一个构造函数(做构造函数链接)调用构造函数吗?)
问题描述
作为 C# 开发人员,我习惯于通过构造函数运行:
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);
    }
}
有没有办法在 C++ 中做到这一点?
Is there a way to do this in C++?
我尝试调用类名并使用this"关键字,但都失败了.
I tried calling the Class name and using the 'this' keyword, but both fail.
推荐答案
C++11:是的!
C++11 及更高版本具有相同的功能(称为 委托构造函数).
C++11 and onwards has this same feature (called delegating constructors).
语法与C#略有不同:
class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {}
};
C++03:否
不幸的是,在 C++03 中没有办法做到这一点,但是有两种方法可以模拟这个:
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
您可以通过默认参数组合两个(或多个)构造函数:
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)
  // ...
};
使用init方法共享通用代码:
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)
{
  // ...
}
请参阅C++FAQ 条目以供参考.
这篇关于我可以从 C++ 中的另一个构造函数(做构造函数链接)调用构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以从 C++ 中的另一个构造函数(做构造函数链接)调用构造函数吗?
				
        
 
            
        - 将函数的返回值分配给引用 C++? 2022-01-01
 - 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
 - GDB 不显示函数名 2022-01-01
 - 将 hdc 内容复制到位图 2022-09-04
 - OpenGL 对象的 RAII 包装器 2021-01-01
 - DoEvents 等效于 C++? 2021-01-01
 - 如何提取 __VA_ARGS__? 2022-01-01
 - XML Schema 到 C++ 类 2022-01-01
 - 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
 - 哪个更快:if (bool) 或 if(int)? 2022-01-01
 
						
						
						
						
						