我很难将其编译.我认为它与静态变量有关,但我不是100%肯定我在做什么.以下是我不断收到的错误消息:
Undefined symbols for architecture x86_64:
“Counter::nCounters”, referenced from:
Counter::Counter(int, int) in main.oCounter::getNCounters() in main.o
Counter::Counter(int, int) in Counter.o
Counter::getNCounters() in Counter.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
这是头文件:
#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程序.任何帮助,将不胜感激.
解决方法:
我相信你需要用一个值来初始化nCounters.
尝试添加
int Counter::nCounters = 0;
在课外的某个地方,或将其初始化为:
static int nCounters = 0;
代替.
原文地址:https://codeday.me/bug/20190826/1726051.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。