我很难将其编译 . 我认为它与静态变量有关,但我不能100%确定我在做什么 . 以下是我不断收到的错误消息:
体系结构x86_64的未定义符号:“Counter :: nCounters”,引用自:main.o中的Counter :: Counter(int,int) . 在main.o中的Counter :: getNCounters()Counter :: Counter(int,int)in Counter.o中的Counter.o Counter :: getNCounters()ld:找不到架构x86_64 clang的符号:错误:链接器命令失败,退出代码为1(使用-v查看调用)
这是头文件:
#ifndef project1_Counter_h
#define project1_Counter_h
class Counter
{
private:
int counter;
int limit;
static int nCounters;
public:
Counter(int, int);
void increment();
void decrement();
int getValue();
static int getNCounters();
};
#endif
这是.cpp文件:
#include "Counter.h"
Counter::Counter(int a, int b)
{
counter = a;
limit = b;
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;
}
而main.cpp只是一个简单的Hello World程序 . 任何帮助,将不胜感激 .
1 回答
我相信你需要用一个值来初始化nCounters .
尝试添加
在课外的某个地方,或者将其初始化为:
代替 .