Paul Dew
Paul Dew

Reputation: 141

C++ overload << (invalid use of non static member)

The problem is that I want output of my program using

Ackermann<M,N>::wartosc;

i wanted to do it by overload operator <<, but when just in main i can type

cout << Ackermann<M,N>::wartosc;

there is a problem too.

here is my code

#include <iostream>
using namespace std;

template<int M, int N>
class Ackermann {
    private:
        int n0, m0; 

        int count(int m, int n)
        {
            if ( m == 0 ) return n+1;
            else if ( m > 0 && n == 0 ){ return count(m-1,1);}
            else if ( m > 0 && n > 0 ) { return count(m-1,count(m,n-1));}   
            return -1;      
        }   
    public:

        Ackermann()
        {
            n0 = N;
            m0 = M;
        }

        int wartosc()
        {
            return count(m0,n0);
        }               

        template<int M1, int N1>
        friend ostream & operator<< (ostream &wyjscie, const Ackermann<M1,N1> &s); 
};


template<int M, int N>
ostream & operator<< (ostream &output, const Ackermann<M,N> &s)         
 {
    return output << Ackermann<M,N>::wartosc;
 }


int main()
{
    Ackermann<3, 3> function;

    cout << function << endl;
    return 0;
}

and the error is

ack.cpp:38:36: error: invalid use of non-static member function ‘int Ackermann<M, N>::wartosc() [with int M = 3, int N = 3]’

Upvotes: 0

Views: 1324

Answers (4)

juanchopanza
juanchopanza

Reputation: 227390

You need to call the member function on instance s:

return output << s.wartosc();
//                        ^^

Next, since you are passing a const reference, you need to make the count and wartosc methods const:

int count(int m, int n) const { .... 

int wartosc() const { ...

Upvotes: 2

Maxime Ch&#233;ramy
Maxime Ch&#233;ramy

Reputation: 18821

I found clang++ error message more understandable:

ack.cpp:37:38: error: call to non-static member function without an object
      argument
    return output << Ackermann<M,N>::wartosc;
                     ~~~~~~~~~~~~~~~~^~~~~~~

You are calling the wartosc like it was a static function but it's not. Replace it by:

return output << s.wartosc;

Upvotes: 1

Drax
Drax

Reputation: 13278

You need to call the member function AND preferably on the instance...

return output << s.wartosc();

Upvotes: 1

crashmstr
crashmstr

Reputation: 28573

It looks like your problem is here: Ackermann<M,N>::wartosc
You are treating it like a static method. Instead change it to use the s parameter passed in.

template<int M, int N>
ostream & operator<< (ostream &output, const Ackermann<M,N> &s)         
{
    return output << s.wartosc;
}

Upvotes: 1

Related Questions