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

How do I get values from a struct in a different cpp file?

本文关键字:结构 获取 文件 cpp      更新时间:2023-10-16

我认为有很多解决方案外面我的问题,但我不明白,我是一种新的结构-所以请帮助我…

好吧,我的问题是我在我的头。h文件中声明了一个结构体,里面也有一个函数,在其中一个结构体值中放入字符串,在头文件中我也可以输出字符串,但我想要那个结构体和那个!!值!!在另一个cpp文件中我可以访问这个值-这是我的代码

header.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返回时,它将被销毁,并且在此之后不再存在。

您可以编写一个函数,该函数通过引用获取FUNCTIONS,并修改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
}