下面的代碼編譯得很好。但是當去連接,爲什麼下面的代碼編譯得很好,但使用靜態鏈接時顯示錯誤
它顯示了以下錯誤
Undefined symbols for architecture x86_64:
"derived::counter", referenced from:
derived::getAddressCounter() in main.cpp.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
我懷疑有什麼錯誤與靜態。但不知道爲什麼。因爲一旦我拿出靜態,代碼鏈接很好。但是靜態在這個代碼中扮演什麼角色?
#include <iostream>
#include <string>
struct base_result { };
struct result : public base_result {
int a;
std::string b;
};
struct base {
static base_result counter;
};
struct derived: public base {
static result counter;
result * getAddressCounter(){
counter.a = 10;
counter.b = "haha";
return &counter;
}
};
int main(){
derived d;
result * ptr;
ptr = d.getAddressCounter();
ptr->a = 20;
ptr->b = "baba";
std::cout << ptr->a << std::endl;
std::cout << ptr->b << std::endl;
return 0;
}
太好了,謝謝。 – 2012-03-09 07:54:13
因此,一個實例變量的正常定義將變成聲明,如果它是靜態變量? – 2012-03-09 08:07:27
沒關係我知道了 – 2012-03-09 08:11:13