c++ - Operator() 作为下标 (C++)

标签 c++ operator-keyword subscript

我这样使用 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% 的保证:

  1. 您传递给赋值函数的值超出了有效范围。
  2. 成员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/

相关文章:

C++动态数组在分配时导致段错误

c++ - 如何通过指针简化重载下标运算符的使用?

swift - 下标使用不明确(Swift 3)

c++ - 构造函数,制作对象

c++ - C++ 概念可以用于在 C++ 中实现混合类型 min 和 max 吗?

c++ - 改进 make 函数的 Swig-tcl 包装

c++ - 如何在派生类中调用基类的<<运算符

C++ Placement new 和构造函数调用

c++ - 如何使用 UML 表示 C++ new() 运算符

ios - 读取字典元素的预期方法在 "class"类型的对象上找不到