Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.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++ 如何从不同cpp文件中的结构获取值?_C++_Struct - Fatal编程技术网

C++ 如何从不同cpp文件中的结构获取值?

C++ 如何从不同cpp文件中的结构获取值?,c++,struct,C++,Struct,我认为我的问题有很多解决方案,但我不明白,我对结构有点陌生,所以请帮助我 好的,我的问题是我在header.h文件中声明了一个struct,里面还有一个函数,它把一个字符串放在一个struct值中,在header文件中我也可以输出字符串,但是我想要这个struct和那个!!价值在一个不同的cpp文件中,我可以访问该值-下面是我的代码 标题.h #include <iostream> #include <string.h> #ifndef FUNCTIONS_H #def

我认为我的问题有很多解决方案,但我不明白,我对结构有点陌生,所以请帮助我

好的,我的问题是我在header.h文件中声明了一个struct,里面还有一个函数,它把一个字符串放在一个struct值中,在header文件中我也可以输出字符串,但是我想要这个struct和那个!!价值在一个不同的cpp文件中,我可以访问该值-下面是我的代码

标题.h

#include <iostream>
#include <string.h>

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

struct FUNCTIONS
{
  std::string f_name;
};
//extern FUNCTIONS globalStruct;

//put in struct variable
void put2struct()
{
  struct FUNCTIONS struct1;
  struct1.f_name = "FUNCTION";
  std::cout << "Functionname: " << struct1.f_name << std::endl;

}

#endif //FUNCTIONS_H
和main.cpp

#include <iostream>
#include <string.h>

#include "header.h"

using namespace std;



int main(int argc, char const *argv[])
{
  struct FUNCTIONS globalStruct;
  put2struct();

  //FUNCTIONS struct1;
  std::cout << "Functionname2: " << globalStruct.f_name << std::endl;
  return 0;
}

我希望有人能帮助我,我真的不明白该怎么做:/

在定义局部变量的块之外,没有办法直接访问它。因为struct1是一个自动变量,所以当put2struct返回时,它将被销毁,此后不再存在

您可以编写一个通过引用获取函数的函数,并修改put2struct以调用该函数。这样,您就可以从不同的cpp文件访问struct1:

void foo(FUNCTIONS&);

void put2struct()
{
    FUNCTIONS struct1;
    // do your thing
    foo(struct1);
}

// another file
void foo(FUNCTIONS& object) {
    // you have access to the object passed by reference
}

为什么函数硬编码一个本地结构而不是接受一个参数?这有什么意义?你可以在函数中使结构成为静态的,然后通过引用返回它。这与结构和文件无关。您需要一本C++的书,特别是关于返回值和范围的部分。我只想看看结构的一个属性是怎么回事。对于Strutt,有更多的属性输入。请只需告诉我获取字符串的方法,我将它放入FAX属性中,在主文件中输出。