C++ 中的问题具有静态变量和函数的类
有人可以告诉我下面的类有什么问题吗,g++ 在 ubuntu 上给出错误:
class FibonacciGenerator { private: static int num1, num2, counting; public: static void Reset() { num1 = 0; num2 = 1; counting = 1; } static int GetCount() { return counting; } static int GetNext() { int val = 0; if(counting == 1) val = num1; else if(counting == 2) val = num2; else { val = num1 + num2; num1 = num2; num2 = val; } counting ++; return val; } };
Can someone tell me what is problem in the following class, g++ is giving errors on ubuntu:
class FibonacciGenerator { private: static int num1, num2, counting; public: static void Reset() { num1 = 0; num2 = 1; counting = 1; } static int GetCount() { return counting; } static int GetNext() { int val = 0; if(counting == 1) val = num1; else if(counting == 2) val = num2; else { val = num1 + num2; num1 = num2; num2 = val; } counting ++; return val; } };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类定义中的语句
static int num1, num2,counting;
并没有定义这些变量,它只是声明它们。如果使用它们,也必须对其进行定义。完整的示例如下:
如果 FibonacciGenerator 在名称空间中声明,则这些静态成员定义也必须位于该名称空间中。
像这样使用静态成员可能是一个非常糟糕的主意。最好将它们设置为实例变量,这样您就可以在代码的不同部分中拥有多个独立的斐波那契生成器。
The statement
static int num1, num2, counting;
in a class definition does not define those variables, it only declares them. If they are used they must also be defined.A complete example of this is as follows:
If FibonacciGenerator is declared in a namespace, then these static member definitions must also be in that namespace.
Using static members like this is probably a very bad idea. It would be better to make them instance variables, so that you could have multiple independent
FibonacciGenerators
in separate parts of the code.您只声明了静态成员。 ,您还应该在 cpp 文件中定义它们
当您在类中编写时
,它只是一个声明,但每个程序都必须包含所使用的每个变量的一个定义(根据“单一定义规则”)。哈
You have only declared the static members. You should also define them in a cpp file like this
when you write
inside a class, it is only a declaration, but every program must contain exactly one definition of every variable that is used (as per the One-Definition-Rule). hth