C++构造函数复习

#include <iostream>

using namespace std;

class Element
{
  public:
    Element(int e = 12) : elem(e)
    {
      cout << "element 1" << endl;
    }
    int elem;
};

class ArrayHelper
{
  public:
    ArrayHelper()
    {
      cout<< "cons 1" << endl;
    }
    ArrayHelper(int size) : val(size)
    {
      cout<< "cons 2" << endl;
    }
    ArrayHelper(const ArrayHelper &other)
    {
      cout<< "cons 3" << endl;
      val = other.val;
    }

    ArrayHelper &operator=(const ArrayHelper &other)
    {
      cout<< "cons 4" << endl;
      val = other.val;
      s = other.s;
      return *this;
    }
  public:
    int val;
    Element s;
};
int main()
{
  ArrayHelper x;
  ArrayHelper m(12);
  ArrayHelper v = m;
  v = m;
  cout<< v.val << endl;
}

另存为test_constructor.cpp,用g++编译运行,结果为:

element 1
cons 1
element 1
cons 2
element 1
cons 3
cons 4
12



你可能感兴趣的:(C++,Class,include)