請看下面的程序。爲什麼我得到一個錯誤?g ++中的C++鏈接錯誤
build/Debug/GNU-Linux-x86/main.o: In function `main':
/home/sb23/pr/main.cpp:14: undefined reference to `serverData::server'
collect2: ld returned 1 exit status
請看下面的程序。爲什麼我得到一個錯誤?g ++中的C++鏈接錯誤
build/Debug/GNU-Linux-x86/main.o: In function `main':
/home/sb23/pr/main.cpp:14: undefined reference to `serverData::server'
collect2: ld returned 1 exit status
靜態成員變量必須在你的.cpp文件的一個存儲分配:
/* static */
int serverData::serverTemp;
int serverData::server;
你有
#include <stdlib.h>
#include <string>
#include <string.h>
#include <iostream>
using namespace std;
class serverData
{
public:
static int serverTemp;
static int server;
};
int main(int argc, char** argv)
{
string s = "sajad bahmani";
serverData::server = 90 ;
const char * a = s.data();
cout << a[0] << endl;
return (EXIT_SUCCESS);
}
中聯,我試圖鏈接時出現此錯誤只是在類中聲明瞭靜態成員,但尚未定義它們。你需要在課堂外定義它們。
//definition
int serverData::serverTemp; //implicitly initialized to 0
int serverData::server = 5; // initialized to 5
你確定第一個被初始化了嗎? – 2010-02-04 14:42:51
@Martin:是的,我很確定。 – 2010-02-04 14:44:35
這是*不* **編譯錯誤**,那就是**鏈接錯誤** – 2010-02-04 14:36:57
使用s.c_str(),以獲得從的std :: string一個 「C風格」 字符串,S .data()不保證以null結尾。 – 2010-02-04 14:39:35