C++重载<<(无效使用非静态成员)

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

本文关键字:lt 静态成员 重载 C++ 无效      更新时间:2023-10-16

问题是我想要使用输出我的程序

Ackermann<M,N>::wartosc;

我想通过重载运算符<lt;,但当我基本上可以键入时

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

还有一个问题。

这是我的代码

#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;
}

错误为

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

您需要调用实例s:上的成员函数

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

接下来,由于要传递const引用,因此需要使countwartosc方法const:

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

看起来您的问题就在这里:Ackermann<M,N>::wartosc
你把它当作一种静态方法。改为使用传入的s参数。

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

您需要在实例上调用成员函数AND。。。

return output << s.wartosc();

我发现clang++错误消息更容易理解:

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

你调用wartosc就像它是一个静态函数,但事实并非如此。替换为:

return output << s.wartosc;