C++ 为什么外部变量需要包含文件?
我发现: 它的主要答案对我来说相当清楚 但是,我不明白为什么这会给我一个错误: x、 h: ---main.cpp---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来覆盖默认值并为其提供外部链接(以便可以从不同的翻译单元访问
#包括“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