如何从不同的cpp文件中的结构中获取值?
How do I get values from a struct in a different cpp file?
我认为有很多解决方案外面我的问题,但我不明白,我是一种新的结构-所以请帮助我…
好吧,我的问题是我在我的头。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
}
相关文章:
- 从字符串中获取结构的大小
- 如何在结构初始化中获取成员C++
- 从 cin 获取 c++ 中结构中多个枚举的输入
- 如何通过向量中的结构 id 获取索引号
- 获取结构 c++ 中元素的索引
- 如何获取结构C++的输入
- 使用加速融合获取结构名称
- 如何使用值获取结构的索引
- 如何获取结构体成员的地址
- 结构化绑定,无需复制即可获取子向量的连续元素
- 在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调
- 获取指向映射内结构的指针
- 从行分析中获取结构
- 在模板实例化期间获取原始结构/类名C++
- 如何从 GIFLIB 保存图像结构中获取 RGB 颜色数据
- 获取结构的 UUID
- 如何直接从 FILETIME 结构获取/设置和获取秒数
- 从知道其结构类型的实例中获取值
- 如何使用结构C++获取从函数中生成的最大值
- 从接口层次结构获取接口