无法在类中返回指针
can't return pointer in class
#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。
相关文章:
- 在函数中返回无符号字符数组,但不返回指针
- 为什么需要返回指针来利用协方差?
- 野牛如何在解析树中返回指针
- 何时返回指针与返回对象的一般经验法则?
- 为什么使用 std::istream_iterator 构造函数返回指针
- 为什么我不能直接从返回指针的函数返回对指针的引用?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 为什么下面的代码段返回指针指向的值而不是指针的地址?
- 使用 map<char,strring> 的迭代器返回指针 map<char,strring>*
- 如何从类成员函数返回指针,例如 size_t * class :: function(); 并使用类析构函数 ~size
- 函数返回动态强制转换的指针,返回指针,就好像它根本没有被转换一样
- 从函数返回对指针的引用与返回指针相同?
- C++ 为什么访问数组中的元素会返回指针?
- 关于函数返回指针
- 返回指针或对私有成员的引用的替代方法
- 从函数返回指针
- 通过从当地的C风格阵列中返回指针来获取一个悬空的指针
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 为什么C 模板功能不支持返回指针
- 返回指针的语句 - 解释它是如何工作的以及为什么