gpt4 book ai didi

c++ - for_each 和 mem_fun_ref 麻烦

转载 作者:行者123 更新时间:2023-11-30 01:44:02 24 4
gpt4 key购买 nike

我用for_each和mem_fun_ref作为例子,但是编译有一些错误,问题是什么

#include<iostream>
#include<algorithm>
#include<set>
#include<iterator>
using namespace std;

class Tst
{
public:
Tst(int a, string b):n(a),s(b)
{}

bool operator<(const Tst& t)const
{
return this->n < t.n;
}

int GetN()const
{
return n;
}

string GetS()const
{
return s;
}

void SetN(int a)
{
n = a;
}

void SetName(string name)
{
s = name;
}

void Print(void)
{
cout <<"n is:" << n <<"\ts is:" << s << endl;
}

private:
int n;
string s;
};

int main(void)
{
typedef set<Tst> TstSet;
TstSet tst;

tst.insert(Tst(10, "abc"));
tst.insert(Tst(1, "def"));
for_each(tst.begin(), tst.end(), mem_fun_ref(&Tst::Print));
return true;
}

:4200: 错误:对‘(std::mem_fun_ref_t) (const Tst&)’的调用没有匹配,是什么原因

最佳答案

std::set 包含的对象是const,因此您只能对它们调用const 函数。您的 Print 函数应标记为 const

关于c++ - for_each 和 mem_fun_ref 麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com