为自定义向量类中的特定元素指定一个值.作为a[5]=3 C++
Assign a value to a specific element in a custom vector class. As a[5] = 3 C++
我目前正在学校用C++做一个练习。目标是编写一个向量类的自己的实现。
从测试文件中,我应该能够给一个元素一个特定的值。
a[5] = 7; // element 5 of vector a should hold value 7.
我不确定我是先打a[5]
还是先打operator =
。
从我自己的班级我有
int myvec::operator[](int i) {
return arr[i];
}
它返回i
处的元素。但我不知道如何给它= 7
的值。
我读到的内容似乎是operator = (this)
内置了某种左操作数?
因此,如果有人能帮我分配元素i
的值,我将非常感激
亲切问候
与其返回新值,不如让它返回对元素的引用:
int& myvec::operator[](int i) {
return arr[i];
}
也可以考虑使用std::size_t
作为索引,而不是int
。
用int& myvec::operator[](int i)
替换int myvec::operator[](int i)
您应该返回对元素的引用来更改它。
您可能还想为const编写另一个重载:
const int& myvec::operator[](int i) const /* const overload */
{
assert(i >= 0);
if(i > myvec.size() ) throw out_of_bound_exception;
return arr[i];
}
int& myvec::operator[](int i) /* Changeable */
{
assert(i >= 0);
if(i > myvec.size() ) throw out_of_bound_exception;
return arr[i];
}
相关文章:
- 作为一个C++新手,我遇到了麻烦
- std::mutex作为一个成员变量对多个线程来说是安全的吗
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- 如何将行的第一个单词作为一个变量,将行的其余部分作为另一个变量进行归档/存储
- Windows 32 API:2个复选框作为一个
- 是否可以将指针传递给运算符,作为一个参数,例如指向函数的指针
- 将数组作为一个参数从一个函数传递到C 中的另一个函数
- 我应该把Boost.Python的.so文件放在哪里,这样我就可以把它作为一个模块导入,以及我如何将它与Python 2
- 将迭代器作为一个参数传递
- 使用Time-Stamp作为一个持久软件的INT可以吗?
- 如何将正则表达式中组的每次迭代都作为一个单独的组
- 在N2073提案的情况下以及作为一个整体的c++模块设计
- 开始一个过程,而不是作为一个孩子
- 将两个字符串作为一个字符串读取
- 将连续字节作为一个整数读取
- 如何使用一个整数数组作为一个无序映射的键
- 实现运算符的正确方法!=用于类外的模板作为一个免费函数
- OpenCV作为一个web服务
- 每隔一行或每一列提取一个特征矩阵作为一个新矩阵
- 哈希作为一个整体