为啥空指针调用函数不报错
想实现一下单例模式,但我发现h_wife为空的情况下是可以调用wife类的marry方法,很奇怪,为啥不报错啊...#include <iostream>
using namespace std;
class Wife
{
public:
void marry()
{
cout << "this:" << this << endl;
cout << "姑娘结婚..." << endl;
}
static Wife* creatWife()
{
if (m_Wife==nullptr)
{
m_Wife = new Wife();
}
return m_Wife;
}
private:
Wife(){ };//私有构造函数
static Wife* m_Wife;
};
Wife* Wife::m_Wife = nullptr;
class husband
{
public:
husband()
{
h_wife = nullptr;
}
//选媳妇方法
void choose()
{
h_wife = Wife::creatWife();
}
//结婚方法
void getMarry()
{
//m_wife = Wife::creatWife();
h_wife->marry();
}
private:
Wife* h_wife;
};
int main()
{
husband m_husband;
m_husband.getMarry();//这里为啥不报错
while (1);
return 0;
}