C++这个和常量对象
C++ this and constant object
你能告诉我为什么这个代码有效吗?replace_if
算法使用了重载运算符()。在主函数中,我创建了IsEqual类的常量对象,所以只应使用常量函数成员。不知怎的,恒常性不起作用,那个操作符被调用了。
#include <iostream>
#include <vector>
#include <algorithm>
class IsEqual {
int value;
public:
IsEqual(int v) : value(v) {}
bool operator()(const int &elem){
this->value=6;
return elem == value;
}
};
int main()
{
const IsEqual tst(2);
std::vector<int> vec = {3,2,1,4,3,7,8,6};
std::replace_if(vec.begin(), vec.end(), tst, 5);
for (int i : vec) std::cout << i << " ";
std::cout<<std::endl;
}
结果:3 2 1 4 3 7 8 5
std::replace_if
将自己复制tst
对象。不需要将其限制为const
。
如果要在算法中使用原始对象,可以使用std::reference_wrapper
。由于它将引用const
对象,这将导致编译器错误,因为它要求运算符为const
:
std::replace_if(vec.begin(), vec.end(), std::ref(tst), 5);
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- C++,如何使用常量对象和非常量对象进行比较?
- 通过从构造函数中的'this'复制的指针改变常量对象
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- C++ 对非常量对象的常量引用和对非常量对象的非常量引用之间的区别
- 算法不适用于非常量对象的const_iterator
- 为什么MSVC14允许声明指向动态未初始化常量对象的指针
- C++中的常量对象或私有/常量数据成员(变量)?
- 将值从指针复制到常量对象参数
- 指向静态常量对象的共享指针?
- 非常量对象的向量似乎在基于范围的 for 循环中被视为常量
- 将unique_ptr作为<Object>unique_ptr<常量对象返回>
- 对非常量对象的常量引用
- 为什么 std::move 适用于常量对象
- 如何最好地初始化和存储常量对象
- 构造常量对象与引用常量对象
- 指向从未变为常量的常量对象的C++指针
- 具有常量对象的代码大小
- 如何使构造函数接受一个非常量对象
- 我真的需要为常量对象实现用户提供的构造函数吗?