Home > Net >  error: invalid use of member <...> in static member function
error: invalid use of member <...> in static member function

Time:03-09

I'm encountering this error when I'm trying to use the content of my map 'freq' declared as a class variable, inside my comparator function for sorting the vector(using map to sort the vector elements by frequency). Can anyone highlight where am i going wrong and what should I do? Here's the code:

class Solution {
    map<int, int> freq;
public:
    static bool comp(int a, int b){
        if(a!=b){
            int c1 = freq[a];
            int c2 = freq[b];
            if(c1!=c2)
                return c1<c2;
            else{
                return a>b;
            }
        }
        return a>b;
    }
    vector<int> frequencySort(vector<int>& nums) {
        for(int i:nums){
            freq[i]  ;
        }
        sort(nums.begin(), nums.end(), comp);
        return nums;
    }
};

Error is: Line 6: Char 22: error: invalid use of member 'freq' in static member function int c1 = freq[a]; ^~~~

CodePudding user response:

In C , calls to static members functions are not bound to any object and thus does not contain any implicit this pointer. On the other hand, each object receives its own set of data members. In your particular example, freq is a data member, comp is a static member function and frequencySort is a non-static member function. Calls to non-static member functions are bound to an object of the class and thus receive an implicit this pointer. The implicit this pointer is used to access data members inside the member function.

Now, in your particular case, the comp static member function cannot access data members without any explicit access to a class object, because there is no implicit this pointer for static member functions.

Making comp a static data member should solve the issue, and is probably what you want.

CodePudding user response:

In C , you cannot access a class member directly in a static function. It has to be relative to a certain object. By that I mean something like this:

freq[a]; // Doesn't work
obj.freq[a]; // Works

So to fix your problem, you can simply remove the static keyword:

/*static*/ bool comp(int a, int b) {

CodePudding user response:

Static member functions are not bound to any object i.e., they do not have a this pointer. As a result we cannot refer to this inside the body of a static member function. This restriction applies to both explicit uses of this as well as to implicit uses of this by calling a non-static member.

To solve this you can either make comp a non-static member function or make freq a static data member.

  • Related