构造函数放在Private

众所周知,外部只能调用class中的Public函数,于是给人一种错觉,构造函数只能放在Public中。
其实不然,如果你想设计一个只能生成一个对象的类,并且,该对象只在需要时声明。
那么你就需要把构造函数放入Private中,问题是如何得到这个类的对象呢?
可以有如下操作:
class Person
{
private:
Person();
public:
Person& getOnePerson(){static Person per; return per;}
}

因为static的变量在整个程序生命周期中只会存在一个,所以就算多次调用该函数,还是只能有一个改类对象。

猜你喜欢

转载自blog.csdn.net/qq_42265158/article/details/83589625