gpt4 book ai didi

c++ - 为什么在全局范围内使用 “extern int a”似乎不可行?

转载 作者:行者123 更新时间:2023-12-02 09:55:34 25 4
gpt4 key购买 nike

main.cpp

#include <iostream>
#include "test.h"
int a = 999;
int main() {
std::cout << a << std::endl;
printa();

return 0;
}

test.h
#include <iostream>
extern const int a;
void printa(void) {
std::cout << a << std::endl;
}

编译并运行后,它可以正常工作

但是当我将main.cpp更改为
#include <iostream>
#include "test.h"
extern int a = 999; //here is the change, I have added extern
int main() {
std::cout << a << std::endl;
printa();

return 0;
}

效果很好,但出现警告。

warning: a initialized and declared



怎么了? 为什么在全局范围内使用“extern int a”似乎不可行?

最佳答案

Why does it seem not OK to using "extern int a" in global scope ?



实际上是“确定”。在 header 中,在全局范围内将变量声明为 extern,一切正常。
  • 初始化变量时,不必重复extern关键字。由于在包含头文件时已经执行了声明,因此该变量在此时(.cpp中)已被称为extern
  • 正如注释中提到的 @ Jarod42 一样,您的const声明和非const初始化不匹配。
  • 如果在声明时初始化extern变量,则extern会过时。 extern的语义是“好吧,我将初始化推迟到其他地方”。因此,警告。

  • 例如:

    。H
    extern int a;       // declaration, as extern (will be initialized somewhere else)
    extern const int b; // example with const

    .cpp
    int a = 42;         // initialization
    const int b = 4422; // initialization

    关于c++ - 为什么在全局范围内使用 “extern int a”似乎不可行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60430573/

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