使用静态变量和函数的C ++类中的问题 [英] Problem in C++ class with static variables and functions
问题描述
有人可以告诉我下面的类是什么问题,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;
}
};
语句 static int num1,num2,counting; code>在类定义中没有定义这些变量,它只声明它们。
一个完整的例子如下:
//开始FibonacciGenerator.hpp
#ifndef FIBONACCI_GENERATOR_HPP
#define FIBONACCI_GENERATOR_HPP
class FibonacciGenerator
{
private:
static int num1,num2,counting;
public:
/ *如上* /
};
#endif // FIBONACCI_GENERATOR_HPP
//结束FibonacciGenerator.hpp
//开始FibonacciGenerator.cpp
#includeFibonacciGenerator.h
int FibonacciGenerator :: num1;
int FibonacciGenerator :: num2;
int FibonacciGenerator :: counting;
//结束FibonacciGenerator.cpp
如果在命名空间中声明了FibonacciGenerator,成员定义也必须在该命名空间中。
使用这样的静态成员可能是一个很糟糕的主意。最好将它们作为实例变量,这样你可以在代码的不同部分有多个独立的 FibonacciGenerators
。
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; } };
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:
//Begin FibonacciGenerator.hpp
#ifndef FIBONACCI_GENERATOR_HPP
#define FIBONACCI_GENERATOR_HPP
class FibonacciGenerator
{
private:
static int num1, num2, counting;
public:
/* as above */
};
#endif //FIBONACCI_GENERATOR_HPP
//End FibonacciGenerator.hpp
//Begin FibonacciGenerator.cpp
#include "FibonacciGenerator.h"
int FibonacciGenerator::num1;
int FibonacciGenerator::num2;
int FibonacciGenerator::counting;
//End FibonacciGenerator.cpp
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.
这篇关于使用静态变量和函数的C ++类中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!