// zidingyi.cpp: 定义控制台应用程序的入口点。
// zidingyi.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include "my_array.h"
using namespace std;
int main()
{
my_array array1(10);
for (int i = 0; i < 10; i++)
{
array1.setData(i, i + 10);
}
cout << "------000000-" << endl;
for (int i = 0; i < 10; i++)
{
cout << array1.getData(i) << " ";
}
cout << endl;
//用深拷贝
my_array array2 = array1;
for (int i = 0; i <array2.getlen(); i++)
{
cout << array2.getData(i) << " ";
}
cout << endl;
//用运算操作符
my_array array3;
array3 = array1;
return 0;
}
#pragma once
#include<iostream>
using namespace std;
class my_array
{
public:
my_array();
my_array(int len);
my_array(const my_array &another);
~my_array();
void setData(int index, int data);
int getData(int index);
int getlen();
void operator=(const my_array &another);
private:
int len;
int *space;
};
#include "stdafx.h"
#include "my_array.h"
my_array::my_array()
{
cout << "my_array 。。。。" << endl;
this->len = 0;
this->space = NULL;
cout << "my_array 。。。。" << endl;
}
my_array::my_array(int len)
{
if (len <= 0)
{
this->len = 0;
return;
}
else {
this->len = len;
this->space = new int[this->len];
cout << "my_array(int len) 。。。" << endl;
}
}
my_array::my_array(const my_array &another)
{
if (another.len >= 0)
{
this->len = another.len;
this->space = new int[this->len];
for (int i = 0; i < another.len; i++)
{
this->space[i] = another.space[i];
}
cout << "调用了拷贝构造函数" << endl;
}
}
my_array::~my_array()
{
if (this->space != NULL)
{
delete[]this->space;
this->space = NULL;
len = 0;
cout << "调用了析构函数" << endl;
}
}
void my_array::setData(int index, int data)
{
if (this->space != NULL)
{
this->space[index] = data;
}
}
int my_array::getData(int index)
{
return this->space[index];
}
int my_array::getlen()
{
return this->len;
}
void my_array::operator=(const my_array &another)
{
if (another.len >= 0)
{
this->len = another.len;
this->space = new int[this->len];
for (int i = 0; i < another.len; i++)
{
this->space[i] = another.space[i];
}
cout << "调用了my_array::operator=(const my_array &another)" << endl;
}
}