我这样使用 operator() 作为下标运算符:
double CVector::operator() (int i) const
{
if (i >= 0 && i < this->size)
return this->data[i];
else
return 0;
}
double& CVector::operator() (int i)
{
return (this->data[i]);
}
当我获取值时它可以工作,但是当我尝试使用赋值时出现错误
a(i) = 1;
UPD:错误文本:
Unhandled exception at 0x651cf54a (msvcr100d.dll) in CG.exe: 0xC0000005: Access violation reading location 0xccccccc0.
最佳答案
正如我在评论中所说,问题在于您的设计有缺陷。我对以下两件事之一做出 100% 的保证:
- 您传递给赋值函数的值超出了有效范围。
- 成员
data
指向内存中的无效空间。
无论哪种情况,我都建议添加:
#include <cassert>
并添加 assert(i >= 0 && i < this->size)
而不是无声的失败:
double CVector::operator() (int i) const
{
assert(i >= 0 && i < this->size);
return this->data[i];
}
double& CVector::operator() (int i)
{
assert(i >= 0 && i < this->size);
return (this->data[i]);
}
关于c++ - Operator() 作为下标 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541663/