为什么以下代码编译正常但链接在使用静态时显示错误

时间:2012-03-09 07:44:43

标签: c++ static

以下代码编译正常。但是当进行链接时,

它显示以下错误

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

2 个答案:

答案 0 :(得分:3)

struct base 
{ 
     static base_result counter; 
}; 

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

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

答案 1 :(得分:1)

与在每个创建的对象中获得保留空间的成员变量相比,静态变量不能仅被声明,它们也需要实现/定义

只需添加行

即可
base_result base::counter;
result derived::counter;

到您的代码,它将编译得很好。这些行指示编译器实际保留空间以存储您先前声明的静态变量。