0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

c++ メンバ関数で error: invalid use of non-static data member

Last updated at Posted at 2021-09-11

概要

c++でclassのメンバ関数でメンバ関数を呼び出そうとした際、

error: reference to non-static member function must be called
std::sort(sorted_members.begin(), sorted_members.end(), Population::compare_inds);

というエラーが出ました。
自作classを格納したstd::vectorを自作関数でsortしようとした際にエラーとなりました

呼び出したい関数は以下です

before.cpp
bool compare_inds(const Individual &left, const Individual &right){
    if (left.rank != right.rank)
       {
        return left.rank < right.rank;
       }
    else{
        return left.nc > right.nc;
        }
}

解決策

メンバ関数compare_indsの前にstaticをつけたら解決しました

after.cpp
static bool compare_inds(const Individual &left, const Individual &right){
    if (left.rank != right.rank)
       {
        return left.rank < right.rank;
       }
    else{
        return left.nc > right.nc;
        }
}

vectorのsortのルールはよくわかっていませんが、classのメンバ変数(std::vector)のsortの条件にメンバ関数を使う際はstaticをつける必要があるみたいです。

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?