Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么外部变量需要包含文件?_C++_Extern - Fatal编程技术网

C++ 为什么外部变量需要包含文件?

C++ 为什么外部变量需要包含文件?,c++,extern,C++,Extern,我发现: 它的主要答案对我来说相当清楚 但是,我不明白为什么这会给我一个错误: x、 h: ---main.cpp--- #包括“stdafx.h” #包括“x.h” 命名空间x{Extnint席;Extn const a;}///而不是包含文件 外部国际一级; int _tmain(int argc,_TCHAR*argv[] { std::cout命名空间范围const变量默认为内部链接(即,仅在该翻译单元内可见)。需要extern来覆盖默认值并为其提供外部链接(以便可以从不同的翻译单元访问

我发现: 它的主要答案对我来说相当清楚

但是,我不明白为什么这会给我一个错误:

x、 h:

---main.cpp---

#包括“stdafx.h”
#包括“x.h”
命名空间x{Extnint席;Extn const a;}///而不是包含文件
外部国际一级;
int _tmain(int argc,_TCHAR*argv[]
{

std::cout命名空间范围
const
变量默认为内部链接(即,仅在该翻译单元内可见)。需要
extern
来覆盖默认值并为其提供外部链接(以便可以从不同的翻译单元访问)我对C++不太熟悉,但我不认为<代码> Extn是const a;(在x.h)和 Extn const A;(在主体.CPP)是相同的。@ CordeleLedio2:为什么?
#pragma once
namespace x {
   class A {
   public:  void func() const;
   };
   // extern A const a;  // cannot move this out of the include file !!!
   // extern int xi;     // fine to remove from here
}
#include "stdafx.h"
#include "x.h"

namespace x { extern int xi; extern const A a ; }  // instead of include file

extern int i;

int _tmain(int argc, _TCHAR* argv[])
{
   std::cout << i << std::endl; // works
   std::cout << x::xi << std::endl; // works

   x::a.func();  

    return 0;
}
#include "stdafx.h"
#include "x.h"

namespace x
{
   void A::func() const
   { std::cout << "x::A::func() called" << std::endl;  }

   const A a;  // Problem if const
   int xi = 234; // works
}
int i = 123;  // works