C++——-类成员数组

//MyArray.h
#pragma once
#include <iostream>
using namespace std;
class MyArray
{
public:
    MyArray();
    MyArray(int len);                   //创建一个len长度的数组
    MyArray(const MyArray &another);    //数据成员含有指针,需要进行深拷贝
    ~MyArray();
    void setData(int index, int data);  //数组赋值函数
    int getData(int index);             //数组输出值函数
    int getLen();                       //获取数组长度
private:
    int len;
    int *space;                        
};
//MyArray.cpp
#include "MyArray.h"
MyArray::MyArray()
{
    cout << "MyArray()..." << endl;
    this->len = 0;
    this->space = NULL;
}

MyArray::MyArray(int len)
{
    if (len <= 0)
    {
        this->len = 0;
        return;
    }
    else
    {
        this->len = len;
        this->space = new int[this->len];
        cout << "MyArray::MyArray(int len)..." << endl;
    }
}

MyArray::~MyArray()
{
    if (this->space != NULL)
    {
        delete[]this->space;
        this->space = NULL;
        len = 0;
        cout << "MyArray::~MyArray()..." << endl;
    }
}

void MyArray::setData(int index, int data)
{
    if (this->space != NULL)
    {
        this->space[index] = data;
    }
}

int MyArray::getData(int index)
{
    return this->space[index];
}

int MyArray::getLen()
{
    return this->len;
}

MyArray::MyArray(const MyArray &another)
{
    if (another.len >= 0) {
        this->len = another.len;
        //深拷贝
        this->space = new int[this->len];
        for (int i = 0 ; i < this->len; i++)
        {
            this->space[i] = another.space[i];
        }
        cout << "MyArray::MyArray(const MyArray &another)..." << endl;
    }
}
//main.cpp
#include <iostream>
#include "MyArray.h"
using namespace std;
int main()
{  
    MyArray array1(10);//开辟10个元素的数组
    //赋值操作
    for (int i = 0; i < 10; i++)
    {
        array1.setData(i, i + 10);
    }
    cout << "---------------" << endl;
    cout << "array1" << endl;
    for (int i = 0; i < 10; i++)
    {
        cout << array1.getData(i) << " ";
    }
    cout << endl;
    MyArray array2 = array1;
    cout << "array2" << endl;
    for (int i = 0; i < array2.getLen(); i++)
    {
        cout << array2.getData(i) << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

 

原文链接: https://www.cnblogs.com/god-for-speed/p/10936653.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++-------类成员数组

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/295778

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午5:13
下一篇 2023年2月15日 下午5:13

相关推荐