2012-03-09 51 views
0

下面的代码编译得很好。但是当去连接,为什么下面的代码编译得很好,但使用静态链接时显示错误

它显示了以下错误

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; 
} 

回答

3
struct base 
{ 
    static base_result counter; 
}; 

只有声明静态成员,您还需要定义一次在你的CPP文件。

良好阅读: What is the difference between a definition and a declaration?

+0

太好了,谢谢。 – 2012-03-09 07:54:13

+0

因此,一个实例变量的正常定义将变成声明,如果它是静态变量? – 2012-03-09 08:07:27

+0

没关系我知道了 – 2012-03-09 08:11:13

1

相较于成员变量,让每一个创建对象的预留空间,静态变量不能只是声明,他们需要的是执行/太定义

线

base_result base::counter; 
result derived::counter; 

只需添加到您的代码,它会编译就好了。这些行指示编译器实际保留空间来存储先前声明的静态变量。

+0

希望我可以选择两个答案 – 2012-03-09 08:11:34

相关问题