zoukankan      html  css  js  c++  java
  • STL中list中push_back(对象)保存对象的内部实现

    STL中list中push_back(对象)保存对象的内部实现

    1. 在容器中,存放的是对象拷贝

      

    #include<iostream>
    #include<list>
    using namespace std;
    
    class A{
        int i;
        static int num;
    public:
        A():i(0){ cout<<"A()" <<endl; num ++;}
        A(int ii):i(ii){ cout<<"A(int)" <<endl; num ++;}
        ~A(){ cout<< "~A" <<endl;}
        A(const A& a){
            i = a.i;
            cout<<"A(const A&)"<<endl;
            num ++;
        }
        A& operator =(const A& a){
            cout<<"operator="<<endl;
            i = a.i;
            return *this;
    
        }
        void print(){
            cout<<i<<endl;
        }
        void printN(){
            cout<< " num = "<<num<<endl;
        }
    };
    
    int A::num = 0;
    
    int main(){
        //A a(1);
        //A b = a;
        //A c;
        //c = a;
        //c.print();
        //a.printN();
        list<A> li;
        li.push_back(A(2));
        list<A>::iterator it = li.begin();
        (*it).printN();
    }
    
    输出结果:
    A(int)//A2临时对象
    A(
    const A&)//li.push_back(A(2))调用其复制构造函数 ~A//离开临时对象作用域A调用其析构函数 num = 2 ~A //程序结束 从输出结果可以看出传到list中的是对象的拷贝。
  • 相关阅读:
    H
    G
    hdu1430魔板
    1104. Don’t Ask Woman about Her Age(数论)
    bellman_ford寻找平均权值最小的回路
    bellman_ford算法
    强联通块tarjan算法
    割点算法
    字符串的最小表示法
    扩展KMP
  • 原文地址:https://www.cnblogs.com/icmzn/p/5054842.html
Copyright © 2011-2022 走看看