深拷贝的使用方法
.h 文件
#pragma once
class Array
{
public:
Array(int count);
Array(const Array &arr);
~Array();
void setcount(int count);
int getcount();
void printAddr();
void printArr();
private:
int m_iCount;
int *m_pArr;
};
.cpp文件
#include "stdafx.h"
#include "array.h"
#include <iostream>
using namespace std;
Array::Array(int count)
{
m_iCount = count;
m_pArr = new int[m_iCount];
for (int i = 0; i < m_iCount; i++)
{
m_pArr[i] = i;
}
cout << "Array::Array()" << endl;
}
Array::Array(const Array& arr)
{
m_iCount = arr.m_iCount;
m_pArr = new int[m_iCount];
for (int i = 0; i < m_iCount; i++)
{
m_pArr[i] = arr.m_pArr[i];
}
cout<<"Array::Array(const Array &arr)" <<endl;
}
Array::~Array()
{
delete[]m_pArr;
m_pArr = NULL;
cout << "Array::~Array()" << endl;
}
void Array::setcount(int count)
{
m_iCount = count;
}
int Array::getcount()
{
return m_iCount;
}
void Array::printAddr()
{
cout << "m.pArr的值是:" << m_pArr << endl;
}
void Array::printArr()
{
for (int i = 0; i < m_iCount; i++)
cout << m_pArr[i] << endl;
}
main函数:
// danyuangonggu.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
#include "array.h"
int main()
{
Array arr1(5);
Array arr2(arr1);
arr1.printArr();
arr2.printAddr();
cout << arr2.getcount() << endl;
system("pause");
return arr2.getcount();
}