. Advertisement .
..3..
. Advertisement .
..4..
I am working with cpp and getting the error message:
c.cpp: In member function ‘int Foo::Count(const string&, const string&) const’:
c.cpp:42:94: error: invalid use of non-static member function
std::vector<Bar>::iterator ToFind = lower_bound(bars.begin(), bars.end(), mybar, comparator);
Here is the detail of the code that I ran:
class Bar
{
public:
pair<string,string> one;
std::vector<string> cars;
Bar(string one, string two, string car);
};
class Car
{
public:
string rz;
Bar* owner;
Car(string car, Bar* p);
};
class Foo
{
public:
Foo ( void );
~Foo ( void );
int Count ( const string & one, const string & two) const;
int comparator (const Bar & first, const Bar & second) const;
std::vector<Bar> bars;
};
int Foo::comparator(const Bar & first, const Bar & second) const{
return first.name < second.name;
}
int Foo::Count ( const string & one, const string & two ) const{
int result=0;
Bar mybar = Bar( one, two, "" );
std::vector<Bar>::iterator ToFind = lower_bound(bars.begin(), bars.end(), mybar, comparator);
if (ToFind != bars.end() && ToFind->one == mybar.one ){
result = ...
}
return result;
}
I need an explanation for the problems I’ve encountered. How to fix invalid use of non-static member function?
The cause:
Above function is not a non-static member function because none of the member variables of Foo is used in it, so the error: ”invalid use of non-static member function” appears.
Solution:
Your error will be solved if
Foo::comparator
is made static or wrapped in astd::mem_fun
object class.lower_bounds()
wants the comparer to be a class object which contains a call operator, such as a functor object or function pointer. You can also use a lambda function if C++11 is being used now or in the future. C++11 also possessesstd::bind
.For instance:
It is easiest to make the comparator function static.
Its name will be
Foo::comparator
when it is invoked inCount
.It is not a non-static function, so it doesn’t make sense.
It is possible to make this a non-member operation, especially if you think that
Foo
might use the comparator.