C++ 用c+中的全局变量初始化+;
我试图阅读下面关于创建可在多个文件之间使用的全局变量的线程,但它不起作用 变量.hC++ 用c+中的全局变量初始化+;,c++,inheritance,global-variables,C++,Inheritance,Global Variables,我试图阅读下面关于创建可在多个文件之间使用的全局变量的线程,但它不起作用 变量.h class fileOne{ private: fileTwo ft[variable1]; public: //some functions... }; class fileTwo{ private: //some variables public: //some functions }; extern const int variable1; file1.h cla
class fileOne{
private:
fileTwo ft[variable1];
public:
//some functions...
};
class fileTwo{
private:
//some variables
public:
//some functions
};
extern const int variable1;
file1.h
class fileOne{
private:
fileTwo ft[variable1];
public:
//some functions...
};
class fileTwo{
private:
//some variables
public:
//some functions
};
classfileone{
私人:
fileTwo ft[variable1];
公众:
//一些功能。。。
};
file2.h
class fileOne{
private:
fileTwo ft[variable1];
public:
//some functions...
};
class fileTwo{
private:
//some variables
public:
//some functions
};
class文件二{
私人:
//一些变量
公众:
//一些功能
};
main.cpp
static const int variable1 = 2; // const int for the size of the ft array of class fileOne
#include "file2.h" // class fileTwo definition is needed for class fileOne
#include "file1.h" // class fileOne has a dependency on class fileTwo
int main(){
fileOne fo; // define a fileOne object named fo
// do more stuff
}
intmain(){
整数变量1=2;
fileOne-fo;
}
当我运行此命令时,编译器会显示以下内容:
错误:数组绑定不是“]”标记之前的整数常量
是否可以声明一个全局变量并以上述方式使用它
另外:这是一个数组吗<代码>文件两英尺[variable1]fileTwo是一个类吗?一个固定大小的数组需要在编译时指定其大小,这意味着只能使用编译时常量。不能使用
extern
ed变量作为数组的大小,即使它被声明为const
,因为编译器根本不知道变量的实际值,因为它位于另一个转换单元中
另外,在main.cpp
中,您不能将extern
'ed变量声明为局部变量,它需要在全局范围内
对于您试图执行的操作,根本没有理由使用extern
。只需在variable.h
中直接用常量值声明variable1
,然后在需要的地方包含该文件,例如:
变量h:
#ifndef变量
#定义变量
静态常量int变量1=2;
#恩迪夫
文件1.h:
\ifndef文件1\u H
#定义文件1_H
#包括“file2.h”
#包括“variable.h”
一类文件{
私人:
fileTwo ft[variable1];
公众:
//一些功能。。。
};
#恩迪夫
文件2.h:
\ifndef文件2\u H
#定义文件2_H
第二类{
私人:
//一些变量
公众:
//一些功能
};
#恩迪夫
main.cpp:
#包括“file1.h”
int main(){
fileOne-fo;
}
是否可以声明一个全局变量并以上述方式使用它
是的,但正如Remy指出的,您需要将此变量移动到头文件中,该头文件将是#include
d fromfile1.h
另外:这是一个数组吗<代码>文件两英尺[variable1]代码>
是的,这叫做C数组。C++标准库还使用C++代码数组(即固定大小),使用如果你想使用C++数组,你可以用这种方式声明:
#include <array>
std::array ft<fileTwo, variable1>;
#包括
std::阵列ft;
要定义数组,需要指定数组的实际大小,并且该大小必须是编译器可以转换为常量的大小。由于variable1
无法转换为常量,编译器会发出错误
你能做的事情如下
file1.h
class fileOne{
private:
fileTwo ft[variable1];
public:
//some functions...
};
class fileTwo{
private:
//some variables
public:
//some functions
};
file2.h
class fileOne{
private:
fileTwo ft[variable1];
public:
//some functions...
};
class fileTwo{
private:
//some variables
public:
//some functions
};
main.cpp
static const int variable1 = 2; // const int for the size of the ft array of class fileOne
#include "file2.h" // class fileTwo definition is needed for class fileOne
#include "file1.h" // class fileOne has a dependency on class fileTwo
int main(){
fileOne fo; // define a fileOne object named fo
// do more stuff
}