お世話になります。
C++のlistを使い、データを追加・降順に並べたいのですが、クラス内で演算子>をオーバーロードするとコンパイルできません。フレンド関数とすればできるのですが、どうしてでしょうか。どうかご教授ください。
#include <iostream>
#include <list>
#include <functional>
using namespace std;
// データクラス
class PersonalInfo {
string name;
int age;
public:
// set
void setParam(string name, int age) {
this->name = name;
this->age = age;
}
// get
void getParam(string *name, int *age) {
*name = this->name;
*age = this->age;
}
★コンパイルエラー
// 演算子 > オーバーロード
//bool operator > (const PersonalInfo & pinf) {
// return (this->age > pinf.age);
//}
★フレンド関数とするとコンパイル・実行共に成功
friend bool operator > (const PersonalInfo& linf, const PersonalInfo& rinf) {
return (linf.age > rinf.age);
}
};
int main() {
list<PersonalInfo> intlist;
string name;
int age;
// データ作成
PersonalInfo pinf[5];
pinf[0].setParam("oda", 31);
pinf[1].setParam("toyotomi", 45);
pinf[2].setParam("tokugawai", 13);
pinf[3].setParam("tokugawaa", 13);
pinf[4].setParam("saigou", 21);
// リストに追加
for(int i = 0; i < 5; i++) {
intlist.push_back(pinf[i]);
}
// リストソート(降順)
intlist.sort(greater<PersonalInfo>());
// 出力
list<PersonalInfo>::iterator it = intlist.begin();
while(it != intlist.end() ) {
(*it).getParam(&name, &age);
cout << "名前:" << name.c_str() << "\t年齢:" << age << endl;
++it;
}
return 0;
}
解決しました。
メンバ関数にconst指定をしてやることで解決しました。
お騒がせしました。
bool operator > (const PersonalInfo & pinf) {
return (this->age > pinf.age);
}
↓
bool operator > (const PersonalInfo & pinf) const{
return (this->age > pinf.age);
}
ツイート | ![]() |