【发布时间】:2014-12-09 05:08:48
【问题描述】:
我正在为班级制作 BST。课堂上有 5 个文件,其中 2 1/2 我无法编辑(作为 OOP 中的练习)。我无法编辑 data.h、driver.cpp 或 bst.cpp 的公共成员。
尝试在我的 data.cpp 文件中使用 strcpy 时遇到一些异常错误。这些是相关的,因为我在 bst.cpp 中的插入函数是从驱动程序发送一个数据对象作为参数。
错误的形式是
Unhandled exception at 0x0F3840D9 (msvcr120d.dll) in asgmt04.exe: 0xC0000005:
Access violation writing location 0x00000000.
这里有一些代码
在 bst.cpp 中
void BST::insert(const Data& data)
{
if (index > capacity)
grow();
if (items[index].isEmpty == true)
{
items[index].data.setName(data.getName());
nItems++;
items[index].isEmpty = false;
items[index].loc = index;
}
else if (data < items[index].data)
{
index = (2 * index) + 1;
insert(data);
}
else
{
index = (2 * index) + 2;
insert(data);
}
}
同样,我无法编辑函数原型,因为它是公共成员。
在data.h中
char const * const getName() const { return name; }
在data.cpp中
void Data::setName(char const * const name)
{
strcpy(this->name, name);
}
我也尝试使用重载的 = 运算符并遇到了同样的问题。调用它的代码看起来像
items[index].data = data; //second arg is the one passed into insert function
在data.cpp中
Data& Data::operator=(const Data& data2)
{
strcpy(this->name, data2.name);
return *this;
}
【问题讨论】:
-
您正在取消引用一个空指针。理想情况下,您可能会通过在调试器中运行来获得它发生的行号。可能是您的 this 指针或您的 this->name 指针。添加要检查的断言。
-
@kec 这似乎是问题所在。不幸的是,数据对象的默认构造函数(我无法更改)将 name 初始化为 NULL,并且我在程序运行时动态初始化它们的整个数组。
标签: c++ exception operator-overloading strcpy