更新时间:2022-04-28 23:08:08
class Foo { private: int _mem; public: Foo() : _mem(0) { CommonConstructor(); } Foo(int mem) : _mem(mem) { CommonConstructor(); } Foo(const Foo& f) : _mem(f._mem) { CommonConstructor(); } // 我们所有的构造器都需要的代码段 void CommonConstructor() { printf("Constructing the object"); } }; |
class Foo2 { private: int _mem; public: // 该构造器调用第二个称为基类构造器的构造器 Foo2() : Foo2(0) { } // 下面这个构造器包含由所有构造器使用的公共代码 Foo2(int mem) : _mem(mem) { printf("Constructing the object"); } Foo2(const Foo2& f) : Foo2(f._mem) { } }; |
注意,早期情况下,如果你想试用一下代理构造函数,应该会出现一个编译错误。请注意,这是由于资源问题缺乏导致的,在现在版本的C++/CLI中可以避免这一错误。
本文转自朱先忠老师51CTO博客,原文链接: http://blog.51cto.com/zhuxianzhong/59847,如需转载请自行联系原作者