在代码向量用法中找不到bug

时间:2012-01-19 05:16:40

标签: c++ string debugging vector

我在这段代码中找不到错误

在函数`BinaryCode :: decode(std :: string)':

undefined reference to `BinaryCode::m_vecStr'
undefined reference to `BinaryCode::m_vecStr'
undefined reference to `BinaryCode::m_vecStr'
undefined reference to `BinaryCode::m_vecStr'
undefined reference to `BinaryCode::m_vecStr'
more undefined references to `BinaryCode::m_vecStr' follow

http://codepad.org/PtZkGx6W

输出位于以上网站:

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;

class BinaryCode{
public:
BinaryCode(void);
~BinaryCode(void);
static vector<string> m_vecStr;

vector<string> decode(string message);

};

BinaryCode::BinaryCode(void){
}
BinaryCode::~BinaryCode(void){
}

vector<string> BinaryCode::decode(string message){
m_vecStr.clear();
char szNone[]={"NONE"};
m_vecStr.push_back(szNone);
m_vecStr.push_back(message);
return m_vecStr;
}

int main(){
BinaryCode bc;
  //cout<<bc.decode("12310122");
return 0;
}

2 个答案:

答案 0 :(得分:1)

这不是一个错误,它是一个链接器错误,它告诉你链接器找不到m_vecStr的定义。

您需要在代码中定义一个静态变量,您刚刚声明它但却忘了定义它 添加以下定义:

vector<string> BinaryCode::m_vecStr;

在源文件中只有一次。

答案 1 :(得分:1)

您必须在类声明之外定义静态成员。尝试在类声明后添加:

vector<string> BinaryCode::m_vecStr;

如果您要在不同的文件中声明您的类,请确保在实现文件中定义静态成员(通常为.cpp),而不是在头文件(.h)中定义。