Single-Case mode

Source: Internet
Author: User

Singleton mode: guarantees that a class has only one instance and provides a global access point to access it

First version:

#include <iostream>using namespace Std;class singleton{   static Singleton s;  You can declare a reference to an object of the class itself in the class definition or to an object of that class, or you can use static to decorate the object   int i;   Singleton (int x): I (x) {};   Singleton (const singleton&);//do not allow copying of   singleton& operator= (singleton&);//Do not allow assignment public:static singleton& instance () {return s;} int GetValue () {return i;} void SetValue (int x) {i=x;}}; Singleton singleton::s (n); int main () {singleton& s=singleton::instance (); Cout<<s.getvalue () <<endl ; singleton& s2=singleton::instance (); S2.setvalue (9); Cout<<s.getvalue () <<endl;//singleton s3= Singleton::instance ();   The error declaration copy constructor is private and does not allow copying of getchar (); return 0;}


A second version:

#include <iostream>using namespace Std;class singleton{int i; Singleton (int x): I (x) {};    Singleton (const singleton&);//Do not allow copy singleton& operator= (singleton&);//Do not allow assignment public:static Singleton & Instance () {   static Singleton s (88);//static object creation within the member function implements Singleton mode   return s;} int GetValue () {return i;} void SetValue (int x) {i=x;}}; int main () {singleton& s=singleton::instance (); Cout<<s.getvalue () <<endl; singleton& s2=singleton::instance (); S2.setvalue (9); Cout<<s.getvalue () <<endl;//singleton s3= Singleton::instance ();   The error declaration copy constructor is private and does not allow copying of getchar (); return 0;}







Single-Case mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.