在类中使用动态数组——编译时接收错误
Using a dynamic array inside a class -- Receiving error at compile time
评论中回答的问题 因为我的声誉,我无法以常规方式回答。我稍后会在回答中补充细节,已经在评论中提到了。谢谢**
大家好-
毫无疑问,你会在这个问题上看到,我是C++的新手,但有一些更高级别语言的经验。(这似乎弊大于利)
对于一个类,我需要为类型为整数的数组创建一个包装器。(在类的这个阶段没有模板)我还需要允许类具有非零的起始索引。我在类中使用一个成员数组来存储我的数据(在类的这一点上还没有向量),并从公共方法进行一些转换以访问适当的内部数组元素。
我遇到的问题是,在编译时我不知道内部数组的大小,所以我将其声明为类全局指针,并在构造函数中设置大小。下面是问题区域的代码片段:
int *list;
safeArray::safeArray(int start, int initialSize)
{
if(initialSize <= 0)
{
throw "Array size must be a positive integer";
}
maxSize = initialSize + 1;
startIndex = start;
endIndex = start + initialSize;
list = new int[maxSize]; // Error thrown here
int *tempArray = new int[maxSize];
copyArray(tempArray);
clearArray();
}
我得到的错误是
Incompatible types in assignment of 'int*' to 'int[0u]'
我不能100%确定int[0u]的类型是什么。这是文字值零吗?u表示无符号?我在调试器中检查了maxSize是否包含一个值,并将其替换为一个常量整数值,结果出现了相同的错误。
因为我的int *tempArray = new int[maxSize];
行有效,我认为这可能与需要同时声明和大小有关,所以我选择了执行memcpy。(这实际上超出了赋值的范围,所以我一定缺少了其他东西)memcpy失败了,因为我似乎在破坏我的其他变量。当我在GDB中打印列表的地址时,它给了我与代码中另一个全局变量相同的地址,所以该路由似乎也超出了赋值范围。
我在其他论坛中看到的常见主题是,不能像其他变量那样分配数组,但我不认为这会包括new
语句。我的假设错了吗?
我目前看到的唯一编译错误是上面提到的,并且我在代码中的每个list = new int[maxSize];
语句中都会看到它。
我的问题是:
int[0u]类型是什么?该类型在哪里生成?它必须来自新的声明,对吧?
在类中使用动态数组资源的最佳方式是什么?除了使用矢量?=)
我想这就是所有相关的信息,但如果我错过了一个关键的数据,我很抱歉。下面是实现代码的其余部分。
/*
* safeArray.cpp
* safearray
*
* Created by Jeffery Smith on 6/1/11.
*
*
*/
#include "safeArray.h"
#include <iostream>
using namespace std;
int startIndex = 0;
int endIndex = 0;
int maxSize = 1;
int currentSize = 0;
int *list;
safeArray::safeArray(int start, int initialSize)
{
if(initialSize <= 0)
{
throw "Array size must be a positive integer";
}
maxSize = initialSize + 1;
startIndex = start;
endIndex = start + initialSize;
list = new int[maxSize]; // Error thrown here
int *tempArray = new int[initialSize + 1];
copyArray(tempArray);
clearArray();
}
safeArray::safeArray(const safeArray &sArray)
{
list = new int[sArray.maxSize];
copyArray(sArray);
startIndex = sArray.startIndex;
endIndex = sArray.endIndex;
maxSize = sArray.maxSize;
currentSize = sArray.currentSize;
}
void safeArray::operator=(const safeArray &right)
{
list = new int[right.maxSize];
copyArray(right);
startIndex = right.startIndex;
endIndex = right.endIndex;
maxSize = right.maxSize;
currentSize = right.currentSize;
}
safeArray::~safeArray()
{
delete [] list;
}
int safeArray::operator[](int index)
{
if(OutofBounds(index))
{
throw "You tried to access an element that is out of bounds";
}
return list[index - startIndex];
}
void safeArray::add(int value)
{
if(this->isFull())
{
throw "Could not add element. The Array is full";
}
currentSize++;
list[currentSize + startIndex];
}
void safeArray::removeAt(int value)
{
if(OutofBounds(value))
{
throw "The requested element is not valid in this list";
}
compressList(value);
currentSize--;
}
void safeArray::insertAt(int location, int value)
{
if(OutofBounds(location) || this->isFull())
{
throw "The requested value is either out of bounds or the list is full";
}
expandList(location, value);
currentSize++;
}
void safeArray::clearList()
{
clearArray();
}
bool safeArray::isFull()
{
return(maxSize == currentSize);
}
int safeArray::length()
{
return currentSize;
}
int safeArray::maxLength()
{
return this->maxSize;
}
bool safeArray::isEmpty()
{
return(currentSize == 0);
}
bool safeArray::OutofBounds(int value)
{
return (value > endIndex || value < startIndex);
}
void safeArray::clearArray()
{
for(int i = 0; i < maxSize; i++)
{
list[i] = 0;
}
currentSize = 0;
}
void safeArray::compressList(int value)
{
for(int i = value; i < endIndex; i++)
{
list[i] = list[i + 1];
}
}
void safeArray::expandList(int location, int value)
{
int tempHolder = list[location];
list[location] = value;
for(int i = location; i < endIndex; i++)
{
tempHolder = list[location];
list[location] = value;
value = tempHolder;
}
}
void safeArray::copyArray(int *srcAddr )
{
memcpy(list, srcAddr, sizeof(int) * maxSize);
}
void safeArray::copyArray(const safeArray &sArray)
{
memcpy(list, &sArray, sizeof(int) * maxSize);
}
这是标题定义:
/*
* safeArray.h
* safearray
*
* Created by Jeffery Smith on 6/1/11.
* Copyright 2011 Accenture. All rights reserved.
*
*/
class safeArray {
public:
safeArray(int,int); //Standard constructor
~safeArray(); //Destructor
int operator[](int);
void operator=(const safeArray&); //Assignment overload
safeArray(const safeArray &sArray); //Copy Constructor
void add(int);
int maxLength();
int length();
bool isFull();
bool isEmpty();
void clearList();
void removeAt(int);
void insertAt(int,int);
protected:
int list[];
int startIndex;
int endIndex;
int maxSize;
int currentSize;
private:
void clearArray();
bool OutofBounds(int);
void expandList(int,int);
void compressList(int);
void copyArray(int*);
void copyArray(const safeArray&);
};
int[0u]
?我相信,在C中,可以在结构的末尾有零长度的数组,从而有效地使用可变大小的结构,但这在C++中是无法做到的。我在你的代码中没有看到任何非法代码。可怕的,是的,非法的,不是。你需要发布safearray.h
的内容,如果它包括标准标题,那么你使用using namespace std;
很容易成为问题的原因。
此外,全局变量也很糟糕。只要把指针放在类中,基本上就不应该使用全局变量,除非你做错了什么。尤其是当它让你面临可变阴影、名称冲突和其他巨大问题时。哦,你应该抛出一个异常类,最好是从std::exception
或std::runtime_error
派生的。没有人会试图抓住const char*
。你不应该使用std
名称空间——你在乞求问题。您不是在调用复制构造函数或赋值运算符,而是使用memcpy来复制元素?您还从赋值运算符开始,在几个地方泄露了内存。
template<typename T> class safe_array {
char* list;
std::size_t arrsize;
void valid_or_throw(std::size_t index) {
if (index <= arrsize) {
throw std::runtime_error("Attempted to access outside the bounds of the array.");
}
public:
safe_array(std::size_t newsize)
: list(NULL) {
size = arrsize;
list = new char[arrsize];
for(std::size_t i = 0; i < arrsize; i++) {
new (&list[i * sizeof(T)]) T();
}
}
safe_array(const safe_array& ref)
: list(NULL) {
*this = ref;
}
safe_array& operator=(const safe_array& ref) {
clear();
arrsize = ref.size;
list = new char[arrsize];
for(std::size_t i = 0; i < arrsize; i++) {
new (&list[i * sizeof(T)]) T(ref[i]);
}
}
T& operator[](std::size_t index) {
valid_or_throw(index);
return static_cast<T&>(list[index * sizeof(T)]);
}
const T& operator[](std::size_t index) {
valid_or_throw(index);
return static_cast<const T&>(list[index * sizeof(T)]);
}
void clear() {
if (list == NULL)
return;
for(std::size_t i = 0; i < size; i++) {
(*this)[i].~T();
}
delete[] list;
list = NULL;
arrsize = 0;
}
std::size_t size() {
return arrsize;
}
bool empty() {
return (list == NULL);
}
~safe_array() {
clear();
}
};
我制作了一个相对快速的示例类,它应该会为您指明更多的方向。它没有提供vector
的所有功能,例如没有自动调整大小或容量缓冲(还有一些其他缺点),我很有信心我可能忘记了几件事,但这只是一个开始。
@neneneba博在评论中帮了我一把。原来我的头文件中有一个旧的int list[]声明,我从未更改过。所以它抛出的编译器错误是由于那里的声明造成的。在那之后,一切都很顺利。
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?