谁能解释为什么以下代码无法编译?至少在g ++ 4.2.4上.
更有趣的是,为什么它会在我将MEMBER转换为int时进行编译?
#include <vector>
class Foo {
public:
static const int MEMBER = 1;
};
int main(){
vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我刚刚写了一个包含一些静态数据成员的类,但现在我收到有关"未定义引用"的错误.为什么这不起作用?我究竟做错了什么?
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
我目前正在尝试将工厂实施为单身人士.我几乎使用了Singleton模式的教科书示例.这是.h文件:
namespace oxygen{
class ImpFactory{
public:
static boost::shared_ptr<ImpFactory> GetInstance();
private:
static boost::shared_ptr<ImpFactory> mInstance;
};
Run Code Online (Sandbox Code Playgroud)
这是.cpp文件:
#include "impfactory.h"
using namespace oxygen;
using namespace boost;
shared_ptr<ImpFactory> ImpFactory::GetInstance(){
if (mInstance.get() == 0)
mInstance = shared_ptr<ImpFactory>(new ImpFactory());
return mInstance;
}
Run Code Online (Sandbox Code Playgroud)
代码编译,但我收到链接器错误:
../../lib/oxygen/liboxygen.so.3.2.4:未定义引用`oxygen :: ImpFactory :: mInstance'
这目前有三名学生难倒.有任何想法吗?
我的代码是Arduinoish.我打开了详细编译,因此我可以验证所有.o文件确实正确地传递给链接器,它们是(下面的链接器命令).这让我相信它是某种语法错误.
谷歌搜索错误"未定义的函数引用"产生了很多结果,如"将foo.o添加到您的链接器命令"等答案,等等.
我希望解决方案就像丢失点或 - >某处一样简单.
我在链接器中的一个文件中收到了这一系列错误:
SerialServoControl.cpp.o: In function `SerialServoControl::send(int, int)':
SerialServoControl.cpp:31: undefined reference to `SerialServoControl::_serial'
SerialServoControl.cpp:31: undefined reference to `SerialServoControl::_serial'
SerialServoControl.cpp.o: In function `SerialServoControl::init(char, char)':
SerialServoControl.cpp:9: undefined reference to `SerialServoControl::_tx'
SerialServoControl.cpp:10: undefined reference to `SerialServoControl::_rx'
Run Code Online (Sandbox Code Playgroud)
.h文件:
#ifndef SERIALSERVOCONTROL_H
#define SERIALSERVOCONTROL_H
#include "NewSoftSerial.h"
class SerialServoControl {
public:
// rx, tx
static NewSoftSerial _serial;//(9, 8);
int _servo_id;
static char _tx;
static char _rx;
static void init(char tx, char rx);
static void send(int servo_id, int angle);
void setup(int servo_id);
void set(int spot); …Run Code Online (Sandbox Code Playgroud) 有人可以告诉我下面的课程中有什么问题,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;
}
};