How To Access Other Class Instance Variable Inside A Static Function
//ClassA.h
Class ClassA
{
private:
UtilityClass utilityCls; // this is the instance 开发者_开发问答that I need to access
virtual void Read();
static bool IsValid(char c);
}
//ClassA.cpp
void ClassA::Read()
{
....
string str = "abcdefg"; // sample only
if(find_if(str.begin(), str.end(), IsValid) == str.end())
{
....
}
}
inline bool IsValid(char c)
{
// There are compile errors When I call functions of Utility class here
// Ex: utilityCls.ProcessData();
return (isalpha(c)); // sample only
}
I really need to access "utilityCls" inside the "IsValid" function. Is there a simple way to do this? Or are there any other way or workaround? Sorry if this is a stupid question. Please help me guys...
You've got a static function. How are you going to access member variables? Either make the variable static or the function non-static.
A static member function is related to the class, not to any instance of that class. It's pretty much like a global function that's been declared a friend of the class (with a kind of odd name that includes the class name tacked on the front).
Bottom line: to access (non-static) data, you need to specify an instance of the class whose data it's going to work with (just like you would with a friend function).
Instead of making IsValid
a global function (which you've accidentally done here) or a member function (which I'm sure was your true intent), make it a functor, and in the functor's constructor pass the instance you want to use.
Like this:
class ClassA
{
private:
UtilityClass utilityCls; // this is the instance that I need to access
virtual void Read();
struct IsValid : public std::unary_function<char, bool>
{
IsValid(UtilityClass& utility) : utility_(utility) {};
bool operator()(char c) const
{
return utility_.ProcessData(c);
}
};
};
Use it like so:
void ClassA::Read()
{
....
string str = "abcdefg"; // sample only
if(find_if(str.begin(), str.end(), IsValid(utilityCls)) == str.end())
{
....
}
}
Static functions of a class are really meta-functions: functions which are of use to the class as a whole, but not to any particular object of the class. Thus they don't have any way to access the members of a particular object, in particular they're missing the implied this
pointer that most member functions contain.
If you need a static class to have access to an object's members, you must explicitly pass a pointer or reference to the object. Usually it's better to make the function non-static.
P.S. Your definition of IsValid is incorrect, it should be inline bool ClassA::IsValid(char c)
.
You can't access an instance variable without first creating an instance of the class. Either make IsValid non static or add code to your static method like
Class a; a.utilityCls.ProcessData();
精彩评论