国外网页设计网站,体球网足球世界杯,建筑模板怎么装,建筑培训内容C中只能有一个实例的单例类
前面讨论的 President 类很不错#xff0c;但存在一个缺陷#xff1a;无法禁止通过实例化多个对象来创建多名总统#xff1a; President One, Two, Three; 由于复制构造函数是私有的#xff0c;其中每个对象都是不可复制的#xff0c;但您的目…C中只能有一个实例的单例类
前面讨论的 President 类很不错但存在一个缺陷无法禁止通过实例化多个对象来创建多名总统 President One, Two, Three; 由于复制构造函数是私有的其中每个对象都是不可复制的但您的目标是确保 President 类有且只有一个化身即有了一个 President 对象后就禁止创建其他的 President 对象。要实现这种功能强大的模式可使用单例的概念它使用私有构造函数、私有赋值运算符和静态实例成员。
提示
将关键字 static 用于类的数据成员时该数据成员将在所有实例之间共享。
将 static 用于函数中声明的局部变量时该变量的值将在两次调用之间保持不变。
将 static 用于成员函数方法时该方法将在所有成员之间共享。要创建单例类关键字 static 必不可少如以下示例程序所示
#include iostream
#include string
using namespace std;class President
{private:President() {}; // private default constructorPresident(const President); // private copy constructorconst President operator(const President); // assignment operatorstring name;public:static President GetInstance(){// static objects are constructed only oncestatic President onlyInstance; return onlyInstance;}string GetName(){ return name; }void SetName(string InputName){ name InputName; }
};int main()
{President onlyPresident President::GetInstance();onlyPresident.SetName(Abraham Lincoln);// uncomment lines to see how compile failures prohibit duplicates// President second; // cannot access constructor// President* third new President(); // cannot access constructor// President fourth onlyPresident; // cannot access copy constructor// onlyPresident President::GetInstance(); // cannot access operatorcout The name of the President is: ;cout President::GetInstance().GetName() endl;return 0;
}输出
The name of the President is: Abraham Lincoln分析
第 2843 行的 main( )包含大量注释演示了各种创建 President 实例和拷贝的方式它们都无法 通过编译。下面逐一进行分析。 34: // President second; // cannot access constructor 35: // President* third new President(); // cannot access constructor 第 34 和 35 行分别试图使用默认构造函数在堆和自由存储区中创建对象 但默认构造函数不可用因为它是私有的如第 7 行所示。 36: // President fourth onlyPresident; // cannot access copy constructor 第 36 行试图使用复制构造函数创建现有对象的拷贝在创建对象的同时赋值将调用复制构造函数但在 main( )中不能使用复制构造函数因为第 8 行将其声明成了私有的。 37: // OnlyPresident President::GetInstance(); // cannot access operator 第 37 行试图通过赋值创建对象的拷贝但行不通因为第 9 行将赋值运算符声明成了私有的。因此 在main( )中 不能创建President类的实例 唯一的方法是使用静态函数GetInstance( )来获取President的实例如第 30 行所示。 GetInstance( )是静态成员类似于全局函数无需通过对象来调用它。GetInstance( )是在第 1419 行实现的 它使用静态变量 onlyInstance 确保有且只有一个 President 实例。 为更好地理解这一点可以认为第 17 行只执行一次静态初始化因此 GetInstance( )返回唯一一个President 实例而不管您如何频繁地调用 President:: GetInstance( )。
该文章会更新欢迎大家批评指正。
推荐一个零声学院的C服务器开发课程个人觉得老师讲得不错 分享给大家LinuxNginxZeroMQMySQLRedis fastdfsMongoDBZK流媒体CDNP2PK8SDocker TCP/IP协程DPDK等技术内容 点击立即学习C/C后台高级服务器课程