Operator() 作为下标 (C++)
我这样使用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编写分配值时出现错误:错误文本:
0x651cf54a 处未处理的异常 CG.exe 中的(msvcr100d.dll):0xC0000005: 访问违规读取位置 0xccccccc0。
I use operator() as a subscript operator this way:
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]);
}
It works when I get values, but I get an error when I try to write assign a value using
a(i) = 1;
UPD: Error text:
Unhandled exception at 0x651cf54a
(msvcr100d.dll) in CG.exe: 0xC0000005:
Access violation reading location
0xccccccc0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如我在评论中所说,问题在于你的设计有缺陷。我对以下两件事之一做出 100% 的保证:
data
指向内存中的无效空间。无论哪种情况,我建议添加:
并添加
assert(i >= 0 && i < this->size)
而不是静默失败:Like I said in my comment, the problem is your flawed design. I make a 100% guarantee on one of two things:
data
is pointing to invalid space in memory.In either case, I would suggest adding:
and adding
assert(i >= 0 && i < this->size)
instead of the silent failures:那是因为您还没有在 double& 中实现错误处理。 CVector::operator() (int i) 就像您对另一个重载
()
的函数所做的那样。将其更改为:
您还应该考虑将其他函数中的错误处理机制从
return 0;
更改为更有意义的内容。That's because you haven't implemented error handling in
double& CVector::operator() (int i)
like you did for the other function which overloads()
.Change it to:
You should also consider changing the error handling mechanism in the other function from
return 0;
to something more meaningful.0xcc
是 MSVC 未初始化的内存字节值。换句话说,您的问题很可能是由于访问未初始化的指针或从未初始化的内存派生的指针造成的。0xcc
is the MSVC uninitialized memory byte value. In other words, your problem is most likely due to accessing an uninitialized pointer or a pointer that was derived from uninitialized memory.问题是您没有在
operator()
的double&
版本中检查超出范围的索引。您可能无法保证
data[i]
指向足够大的i
的有效内存地址。您应该检查索引是否超出范围并抛出一些异常,或者调整向量的大小(通过为data
分配更多内存)以能够容纳更多值。The problem is that you do not check for out-of-range index in your
double&
version ofoperator()
.You probably cannot guarantee that
data[i]
points to a valid memory address for a large enoughi
. You should either check for out-of-range index and throw some exception or resize your vector (by allocating more memory dodata
) to be able to hold more values.