拷贝构造函数举例

#include<iostream>
using namespace std;

class IntSet
{
public:
    int *elts;
    int numElts;
    int sizeElts;
    IntSet(int size = 100);//构造函数
    IntSet(const IntSet &is);//拷贝构造函数
    void Display();
};

IntSet::IntSet(int size)
{
    sizeElts = size;
}

void IntSet::Display()
{
    for (int i = 0; i < numElts; i++)
    {
        cout << elts[i] << " ";
    }
}

IntSet::IntSet(const IntSet & is)
{//拷贝构造函数
    numElts = is.numElts;
    sizeElts = is.sizeElts;
    elts = new int(sizeElts);
    for (int i = 0; i < numElts; i++)
    {
        *(elts + i) = *(is.elts + i);
    }
    *elts = *(is.elts);
}

int main()
{
    int a[10] = { 1,2,3 };
    IntSet i1(10);
    i1.elts = a;
    i1.numElts = 3;
    i1.Display();
    cout << "\n---------------------------" << endl;
    IntSet i2(i1);
    i2.Display();
    system("pause");
    return 0;
}

 

posted @ 2017-03-31 15:09  不见x的心  阅读(378)  评论(0编辑  收藏  举报