C++重载<<(无效使用非静态成员)
C++ overload << (invalid use of non static member)
问题是我想要使用输出我的程序
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
引用,因此需要使count
和wartosc
方法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;
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- C++:是否可以使用非静态成员变量模板?
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在复杂继承中访问静态成员变量
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 静态成员变量不会由 gettext 转换
- decltype:使用指针访问类的静态成员
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 如何在C++中定义静态成员结构