c++ constructor, copy constructor, operator =

// list::push_back
#include <iostream>
#include <list>

class element{
private:
    int number;
public:
    element(int number){
        this->number = number;
        std::cout << "constructor used" << std::endl;
    }
    
    element(const element&){
       std::cout << "copy constructor used" << std::endl; 
    }
    element& operator=(const element& element_instance){
        std::cout << element_instance.number << "operator=" << std::endl;
        this->number = element_instance.number;
        return *this;
    }
    int get_number(){
        return this->number;
    }
    ~element(){
        std::cout << this->number << std::endl;
        this->number = 0;
        std::cout << "destructor used" << std::endl;
    }
};

int main ()
{
  std::list<element> mylist;
  int myint;

  std::cout << "Please enter some integers (enter 0 to end):\n";

  do {
    std::cin >> myint;
    element* element_instance = new element(myint);
    mylist.push_back (*element_instance);
    delete element_instance;
  } while (myint);

  //std::cout << "mylist stores " << mylist.size() << " numbers.\n";
  std::cout << "first number:" << (mylist.front().get_number()) << std::endl;

  return 0;
}

 

posted @ 2018-08-18 18:25  友哥  阅读(126)  评论(0编辑  收藏  举报