简体   繁体   English

C++ 将变量从.cpp 传递到 header 文件

[英]C++ pass variable from .cpp to header file

this relates to a question i asked previously: C++ array in header file这与我之前提出的一个问题有关: header 文件中的 C++ 数组

in the main.cpp file there is a variable called fin1在 main.cpp 文件中有一个名为 fin1 的变量

ifstream fin1("ACW2_data.txt");

this might be a stupid question, but how can i use the value of this variable from main.cpp in the header file?这可能是一个愚蠢的问题,但是我如何在 header 文件中使用 main.cpp 中的这个变量的值? (ie. is there a way to pass variables between the two files?) (即有没有办法在两个文件之间传递变量?)

any other info about using header files may help有关使用 header 文件的任何其他信息可能会有所帮助

Thanks in advance提前致谢

This variable can be declared in the header file as an extern .这个变量可以在 header 文件中声明为extern

extern ifstream fin1;

Now you can use this variable wherever you #include this header file including the header file itself.现在你可以在任何地方使用这个变量#include这个 header 文件,包括 header 文件本身。 You don't need to pass the variable as such.您不需要像这样传递变量。 :) :)

I think you need to back up and explain what you are trying to do.我认为您需要备份并解释您要做什么。 Header files are, in general, for defining common definitions and declarations. Header 文件通常用于定义通用定义和声明。

What do you mean by "use the value in the header file"? “使用 header 文件中的值”是什么意思? In general, the header file is not where code is run.通常,header 文件不是运行代码的位置。 So what needs to use this variable there?那么有什么需要使用这个变量呢?

Generally speaking, variables that need to be used in more than one file should be declared in the header to begin with.一般来说,需要在多个文件中使用的变量应该在 header 开头声明。 In C++, this is normally in the form of class members.在 C++ 中,这通常是 class 成员的形式。

Even more common is to pass variables as arguments when another function or method needs to use the same value.更常见的是当另一个 function 或方法需要使用相同的值时,将变量作为 arguments 传递。

I can't tell from the information you've provided, but it sounds like you're on the wrong track to me.我无法从你提供的信息中看出,但听起来你走错了路。

Declare this variable as extern.将此变量声明为 extern。

extern ifstream fin1;

Than every time you change it it value gonna update and be ready in your header file And you can include tour header every where and use that variable每次更改它时,它的值都会更新并准备好在您的 header 文件中并且您可以在任何地方包含游览 header 并使用该变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM