using namespace std;
class A{
public://公有构造函数
A(){
cout << "private is not ok" << endl;
}
};
int main()
{
A *a = new A;
return 0;
}
编译通过
#include<iostream>
using namespace std;
class A{
private://私有构造函数
A()
{
cout << "private is ok" << endl;
}
};
int main()
{
A *a = new A;
return 0;
}
编译错误(new需要调用它的构造函数,当设为私有无法调用)当构造函数设为私有成员变量时,可以通过友元函数或友元类来调用构造函数!
如:
#include<iostream>
using namespace std;
class A{
//private:
public:
A()
{
cout << "private is ok" << endl;
}
public:
friend A* getA();
};
A* getA(){
return new A;
}
int main()
{
A *a = getA();
return 0;
}
当将构造函数和析构函数设为私有或保护类的时候,能够很好的防止客户自定义或被继承子类调用
#include<iostream>
using namespace std;
class A{
private:
A()
{
cout << "private is ok" << endl;
}
};
class B:public A{
};
int main()
{
A *a = new B;
return 0;
}
所以上面这个代码编译不能通过