//myarray.h
#ifndef MYARRAY_H
#define MYARRAY_H
class MyArray
{
private:
int m_length;
int* m_space;
public:
MyArray(int length);
MyArray(const MyArray& array);
int getLength();
void setData(int index,int value);
int getData(int index);
void distroy();
};
#endif // MYARRAY_H
//myarray.cpp
#include "myarray.h"
#include <stdio.h>
MyArray::MyArray(int length)
{
if(length >0)
{
m_length = length;
m_space = new int[m_length];
}
}
MyArray::MyArray(const MyArray &array)//自定义拷贝构造函数
{
delete[] this->m_space;
this->m_length = array.m_length;
this->m_space = new int[this->m_length];
for(int i=0;i<this->m_length;i++)
{
this->m_space[i] = array.m_space[i];
}
}
int MyArray::getLength()
{
return m_length;
}
void MyArray::setData(int index, int value)
{
if(index < m_length)
{
m_space[index] = value;
}
else
{
printf("the index > the lenght...\n");
}
}
int MyArray::getData(int index)
{
int ret = -1;
if(index < m_length)
{
ret = m_space[index];
}
else
{
printf("the index > the lenght...\n");
}
return ret;
}
void MyArray::distroy()
{
m_length = -1;
delete[] m_space;
}
//main.cpp
#include <iostream>
#include "myarray.h"
using namespace std;
int main()
{
MyArray a1(10);
for(int i=0;i<a1.getLength();i++)
{
a1.setData(i,i+1);
}
for(int i=0;i<a1.getLength();i++)
{
cout << a1.getData(i) << endl;
}
cout << "a2" << endl;
MyArray a2(3);
for(int i=0;i<a2.getLength();i++)
{
a2.setData(i,i+1);
}
for(int i=0;i<a2.getLength();i++)
{
cout << a2.getData(i) << endl;
}
cout << "a2(a1)" << endl;
a2 = a1; //这里不能使用a2(a1)来执行深拷贝构造函数,这里是使用编译器提供的拷贝构造函数,而不是自定义的拷贝构造函数
for(int i=0;i<a2.getLength();i++)
{
cout << a2.getData(i) << endl;
}
cout << "a3(a2)" << endl;
MyArray a3(a2);//这里也可以使用a3=a2来执行深拷贝构造函数
for(int i=0;i<a3.getLength();i++)
{
cout << a3.getData(i) << endl;
}
a1.distroy();
a2.distroy();//如果没有深拷贝构造函数,仅使用编译器提供的浅拷贝构造函数,当a1.distroy()结束时,导致后面a2就会重复释放a1
a3.distroy();
cout << "---end---" << endl;
return 0;
}
类数组是啥子????
//mytest.h
#ifndef MYTEST_H
#define MYTEST_H
class MyTest
{
public:
MyTest(int v);
MyTest(const MyTest& t);
void print();
private:
int m_i;
int m_j;
int m_k;
};
#endif // MYTEST_H
//mytest.cpp
#include "mytest.h"
#include <stdio.h>
MyTest::MyTest(int v)
{
m_i = m_j = m_k = v;
}
MyTest::MyTest(const MyTest& t) //深拷贝
{
this->m_i = t.m_i;
this->m_j = t.m_j;
this->m_k = t.m_k;
}
void MyTest::print()
{
printf("i=%d,j=%d,k=%d\n",m_i,m_j,m_k);
}
void test_02()
{
MyTest t1(2); //自动调用构造函数
t1.print();
MyTest t2 = 3; //自动调用构造函数
t2.print();
MyTest t3 = MyTest(4); //手自动调用构造函数
t3.print();
MyTest tA[4] = {MyTest(1),MyTest(2),MyTest(3),MyTest(4)};//类数组:需要手自动调用构造函数
for(int i=0;i<4;i++)
{
tA[i].print();
}
t1 = t2; //t1 = 1;
t1.print();
}