C++ 静态变量给出错误
C++ Static Variable giving error
我正在学习 C++,但我正在处理的实验室遇到了一个奇怪的问题。在我似乎没有正确引用事物的地方是我的猜测。
它基本上会抛出一个错误,比如找不到在 Class 头文件中声明的 static int nCounters。
//counter.h
开始
class Counter
{
private:
int counter;
int limit;
static int nCounters;
public:
Counter(int x, int y);
void increment();
void decrement();
int getValue();
int getNCounters();
};
//counter.h
结束
//counter.cpp
开始
#include "counter.h"
Counter::Counter(int x, int y)
{
counter = x;
limit = y;
nCounters++;
}
void Counter::increment()
{
if (counter < limit)
{
counter++;
}
}
void Counter::decrement()
{
if (counter > 0)
{
counter--;
}
}
int Counter::getValue()
{
return counter;
}
int Counter::getNCounters()
{
return nCounters;
}
//counter.cpp
结束
//counter_test.cpp
开始
#include <iostream>
#include "counter.cpp"
using namespace std;
int main(){
Counter derp(5,5);
cout << derp.getValue();
return 0;
}
//counter_test.cpp
结束
您需要 define
static
变量。 static int nCounters;
只是声明而非定义。
这样定义
int Counter :: nCounters;
例如
class Counter {
private:
static int nCounters; /*declaration */
public:
/* Member function of class */
};
int Counter :: nCounters;/*definition, this is must */
int main() {
/* some code **/
return 0;
}
由于此变量在所有 类 中都是相同的,并且在实例化 Counter
时未定义,这与普通成员变量不同,因此您必须在代码中的某处添加以下行(最佳放置在 counter.cpp
):
Counter::nCounters = 0;
这会设置 nCounters
的定义和初始值。
附带说明,#include "counter.cpp"
是不好的做法。相反 #include "counter.h"
和 link 将 .cpp
文件添加到您的可执行文件中。
我正在学习 C++,但我正在处理的实验室遇到了一个奇怪的问题。在我似乎没有正确引用事物的地方是我的猜测。
它基本上会抛出一个错误,比如找不到在 Class 头文件中声明的 static int nCounters。
//counter.h
开始class Counter
{
private:
int counter;
int limit;
static int nCounters;
public:
Counter(int x, int y);
void increment();
void decrement();
int getValue();
int getNCounters();
};
//counter.h
结束//counter.cpp
开始#include "counter.h"
Counter::Counter(int x, int y)
{
counter = x;
limit = y;
nCounters++;
}
void Counter::increment()
{
if (counter < limit)
{
counter++;
}
}
void Counter::decrement()
{
if (counter > 0)
{
counter--;
}
}
int Counter::getValue()
{
return counter;
}
int Counter::getNCounters()
{
return nCounters;
}
//counter.cpp
结束//counter_test.cpp
开始#include <iostream>
#include "counter.cpp"
using namespace std;
int main(){
Counter derp(5,5);
cout << derp.getValue();
return 0;
}
//counter_test.cpp
结束您需要 define
static
变量。 static int nCounters;
只是声明而非定义。
这样定义
int Counter :: nCounters;
例如
class Counter {
private:
static int nCounters; /*declaration */
public:
/* Member function of class */
};
int Counter :: nCounters;/*definition, this is must */
int main() {
/* some code **/
return 0;
}
由于此变量在所有 类 中都是相同的,并且在实例化 Counter
时未定义,这与普通成员变量不同,因此您必须在代码中的某处添加以下行(最佳放置在 counter.cpp
):
Counter::nCounters = 0;
这会设置 nCounters
的定义和初始值。
附带说明,#include "counter.cpp"
是不好的做法。相反 #include "counter.h"
和 link 将 .cpp
文件添加到您的可执行文件中。