gpt4 book ai didi

c++ - 为什么以下代码可以正常编译,但在使用 static 时链接显示错误

转载 作者:行者123 更新时间:2023-11-27 23:25:47 25 4
gpt4 key购买 nike

以下代码可以正常编译。但是什么时候去链接,

显示如下错误

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

最佳答案

struct base 
{
static base_result counter;
};

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

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

关于c++ - 为什么以下代码可以正常编译,但在使用 static 时链接显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com