求和(单例模式,初始化列表,容器,迭代器)

来源:互联网 发布:虚拟货币挖矿网站源码 编辑:程序博客网 时间:2024/06/06 02:22

使用单例模式,初始化列表,容器,迭代器

在单例模式构造函数是可以private的,用静态成员函数GetInstance来获得实例。

单例模式:作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

 单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例

#include <iostream>
#include <vector>
using namespace std;

class sum
{
public:
 const int num ;
 

 void  toSum( );
    static sum * getInstance()
 {
  if( NULL == pInstance )
   pInstance = new sum();
     return pInstance;
 }
private:
    static sum* pInstance ;

 sum():num( 100 )
 {}
};

 
 void sum::toSum(  )
 {
     int i;
  int t = 0;
  vector<int> v;
  for ( i = 0; i < num ; i++ )
         v.push_back( i + 1 );

  vector<int>::iterator it=v.begin();
  while(it != v.end() )
  {
      t = t + *it;
   it++;
  }
  cout << t << endl;
 }

sum* sum::pInstance = NULL ; 

 void main()
{
 sum::getInstance()->toSum();
    delete sum::getInstance();
}