zoukankan      html  css  js  c++  java
  • Python中的闭包

    简单的闭包的栗子:

    def counter(statr_at = 0):
    	count = 1
    	def incr():
    		nonlocal count #注意由于count类型为immutable,所以需要声明清楚在此局部作用域内引用的是外部作用域那个count
    		count += 1
    		return count
    	return incr
    
    >>> count = counter(4)
    >>> count()
    2
    >>> count()
    3
    >>> count()
    4
    >>> count()
    5
    >>> count()
    6
    >>> count()
    7
    >>> count()
    8
    >>> count()
    9
    >>> count()
    10
    >>> count()
    11
    

     这种行为可用C++11模拟如下:

    #include<iostream>
    #include<memory>
    using namespace std;
    class Count{
    public:
     Count(const shared_ptr<int>& p) :sp(p){}
     int operator()(){
      (*sp)++;
      return (*sp);
     }
    private:
     shared_ptr<int> sp;
    };
    Count func(int k){
     shared_ptr<int> sp = make_shared<int>(k);
     return Count(sp);
    }
    int main(){
      auto c = func(10);
      cout << c() << endl;
      cout << c() << endl;
      cout << c() << endl;
     return 0;
    }
    
  • 相关阅读:
    了解jQuery
    了解JavaScript
    了解DOM
    了解CSS
    UICollectionViewCell点击高亮效果(附带效果GIF)
    产品迭代缓慢的原因
    了解Web的相关知识
    HTML常用标签
    HTML常用标签效果展示
    了解数据产品经理
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4608043.html
Copyright © 2011-2022 走看看