Constructor chaining in C++(C++中的构造函数链)
问题描述
我对构造函数链的理解是,当一个类中有多个构造函数(重载的构造函数)时,如果其中一个试图调用另一个构造函数,那么此过程称为 CONSTRUCTOR CHAINING ,C++ 不支持该过程.最近我在看网上资料的时候看到了这一段……是这样的……
My understanding of constructor chaining is that , when there are more than one constructors in a class (overloaded constructors) , if one of them tries to call another constructor,then this process is called CONSTRUCTOR CHAINING , which is not supported in C++ . Recently I came across this paragraph while reading online material.... It goes like this ...
您可能会发现自己想要编写一个成员函数来将类重新初始化为默认值.因为您可能已经有一个执行此操作的构造函数,所以您可能会尝试从您的成员函数调用构造函数.如前所述,链接构造函数调用在 C++ 中是非法的.您可以从函数中的构造函数复制代码,这会起作用,但会导致代码重复.在这种情况下,最好的解决方案是将代码从构造函数移到新函数中,并让构造函数调用您的函数来完成初始化数据的工作.
You may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data.
调用构造函数的成员函数是否也属于构造函数链??请在 C++ 中阐明这个主题.
Does a member function calling the constructor also come under constructor chaining ?? Please throw some light on this topic in C++ .
推荐答案
该段基本上是这样说的:
The paragraph basically says this:
class X
{
void Init(params) {/*common initing code here*/ }
X(params1) { Init(someParams); /*custom code*/ }
X(params2) { Init(someOtherParams); /*custom code*/ }
};
您也不能从成员函数调用构造函数.你可能觉得你已经做到了,但那是一种错觉:
You cannot call a constructor from a member function either. It may seem to you that you've done it, but that's an illusion:
class X
{
public:
X(int i):i(i){}
void f()
{
X(3); //this just creates a temprorary - doesn't call the ctor on this instance
}
int i;
};
int main()
{
using std::cout;
X x(4);
cout << x.i << "
"; //prints 4
x.f();
cout << x.i << "
"; //prints 4 again
}
这篇关于C++中的构造函数链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++中的构造函数链
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01