C这和恒定的对象

C这和恒定的对象,第1张

概述你能告诉我为什么这段代码有效吗?有重载的operator()由replace_if算法使用.在main函数中,我创建了IsEqual类的常量对象,因此只应使用常量函数成员.某种程度上,constancy不起作用,并且该运算符被调用. #include <iostream>#include <vector>#include <algorithm>class IsEqual { int 你能告诉我为什么这段代码有效吗?有重载的operator()由replace_if算法使用.在main函数中,我创建了IsEqual类的常量对象,因此只应使用常量函数成员.某种程度上,constancy不起作用,并且该运算符被调用.
#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(),std::ref(tst),5);
总结

以上是内存溢出为你收集整理的C这和恒定的对象全部内容,希望文章能够帮你解决C这和恒定的对象所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1256087.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存