C++ 类构造函数重载之间互相调用(或不能互相调用),构造函数间的调用会创建不同的类的对象实例,有可能导致达不到预期初始化效果。与C#/JAVA等有差异
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"A():"<<this<<endl;
A("DEFAULT NAME");
}
A(string name)
{
cout<<"A(string name):"<<this<<endl;
this->m_s_name=name;
}
void Show()
{
cout<<"Show():"<<this<<"\t"<<"Name:"<<this->m_s_name<<endl;
}
private:
string m_s_name;
};
int main()
{
A a;
a.Show();
A b("Cicall");
b.Show();
cin.get();
return 0;
}
输出:
- A():0x6efebc
- A(string name):0x6efdfc
- Show():0x6efebc Name: // name变量赋值未达到预期
- A(string name):0x6efea4
- Show():0x6efea4 Name:Cicall
本文探讨了C++中构造函数重载互相调用的问题,通过具体示例展示了这种调用可能导致的初始化异常,与C#/JAVA等语言存在差异。深入理解构造函数调用机制对于避免此类错误至关重要。
1479

被折叠的 条评论
为什么被折叠?



