无法在类中返回指针

can't return pointer in class

本文关键字:返回 指针      更新时间:2023-10-16
#include "C_IntArray.h"
C_IntArray::C_IntArray()
{
    m_Array = 0;
    m_Length = 0;
}
C_IntArray::~C_IntArray(void)
{
    delete m_Array;
    m_Length = 0;
}
void C_IntArray::ContructorWithParater(int *intArray, int size)
{
    m_Array = new int[size];
    m_Length = size;
    for (int i = 0; i < size; i++)
        m_Array[i] = intArray[i];
}
void C_IntArray::InputArray()
{
    cout << "Nhap so luong phan tu: ";
    cin >> m_Length;
    m_Array = new int [m_Length];
    for(int i = 0; i < m_Length; i++)
    {
        cout << "Nhap phan tu Array[" << i << "] = ";
        cin >> m_Array[i];
    }
}
void C_IntArray::OutputArray()
{
    for(int i = 0; i < m_Length; i++)
        cout << m_Array[i] << " ";
}
C_IntArray C_IntArray::Remove(int x)
{
    C_IntArray temp;
    temp.ContructorWithParater(m_Array, m_Length);
    temp.OutputArray();
    for(int i = 0; i < temp.m_Length; i++)
    {
        if(temp.m_Array[i] == x)
        {
            {
                temp.m_Length--;
                for(int j = i; j < temp.m_Length; j++)
                    temp.m_Array[j] = temp.m_Array[j + 1];
            }
        }
        cout << "n";
        temp.OutputArray();
    }
    cout << "n";
    return temp;
}

文件头

#include <iostream>
using namespace std;
#ifndef _C_IntArray_h
#define _C_IntArray_h
class C_IntArray
{
private:
    int *m_Array, m_Length;
public:
    C_IntArray();
    ~C_IntArray();
    // khoi tao tham so dau vao
    void ContructorWithParater(int *, int);
    void InputArray();
    void OutputArray();
    // xoa phan tu trung
    C_IntArray Remove(int );
};
#endif _C_IntArray_h;

文件主

#include "C_IntArray.h"
void main()
{
    C_IntArray a;
    a.InputArray();
    int giaTriCanXoa = 5;
    C_IntArray b = a.Remove(giaTriCanXoa);
    b.OutputArray();
    cout << "n";
    a.OutputArray();
    system("pause");
}

我尝试调试我的项目。 函数 Remove 在类中是工作,当我调试返回 temp 时它仍然有效,但我接下来是调试它返回 NULL 或返回 1 个数组函数 删除 在类中无法返回临时。

如果我删除析构函数或我的临时温度是静态C_IntArray,我的项目可以运行。

如果我拼错了帮助人们修复的愿望。感谢您的关注。

Remove 返回类的副本,而不是指针。 因此,它是一个副本。由于您没有定义复制构造函数或赋值运算符,因此您将使用默认的复制/赋值 - 这将导致m_Array被多次删除。

您可以在复制类时执行内部数组的深层复制,也可以使用写入时复制和引用计数。

即您需要添加以下功能:

C_IntArray(C_IntArray const& other);
C_IntArray& operator=(C_IntArray const& rhs);

他们应该为数组中的数据分配新的存储空间,并从"其他"或"rhs"复制元素。 查找如何编写复制构造函数或赋值运算符。 网上会有无数的例子。

您的类中也有内存泄漏。C_IntArray::InputArray(( 会泄漏内存,因为在为其分配新内存之前不会删除m_Array。

最好

使用自由函数进行输入任务,而不是使其成为类成员 - 保持类的接口最小且完整。

即将它移出类:

void InputArray(C_IntArray& dst) {
    // ...
}

正如其他人所建议的,只需使用std::vector。