c++ - 从 C++ 中的另一个文件访问向量或数组
问题描述
我正在尝试从另一个文件(此处为pattern.cpp)访问数组/向量的元素。根据这个讨论(http://cplusplus.com/forum/beginner/183828/)我应该做
//pattern.cpp
namespace myprogram {
void Pattern::FromReal()
{
extern std::vector<double> real_data;
for (auto it=real_data.begin(); it !=real_data.end(); it++)
std::cout<<" my vector "<< *it <<" ";
}
}
and the vector is here
//RealData.cpp
#include <vector>
std::vector<double> real_data{ 0., 0., 1.46, 1.51, 1.55, 1.58, 1.45, 1.48, 1.54, 1.54, 1.60, 1.56};
当我编译我得到这个错误
<directory>/x86_64/Gcc/gcc620_x86_64_slc6/6.2.0/x86_64-slc6/include/c++/6.2.0/bits/stl_iterator.h:770: undefined reference to `myprogram::real_data'
collect2: error: ld returned 1 exit status
我使用 CMake 并且 RealData.cpp 已经添加到 CMakeList 中。这里有什么问题?我应该改变什么?
解决方案
这是工作示例。只需创建(如果还没有)一个包含向量的 realdata.hextern
文件real_data
。然后你可以在 pattern.cpp 和任何你想要这个real_data
向量的地方包含这个头文件,比如在 main.cpp 中。
主文件
#include <iostream>
#include "pattern.h"
#include "realdata.h"
extern std::vector<double> real_data;
int main()
{
std::cout<<"Size of vector from other file is: "<<real_data.size()<<std::endl;
myprogram::Pattern obj;
obj.FromReal();
return 0;
}
模式.h
#ifndef PATTERN_H
#define PATTERN_H
namespace myprogram {
class Pattern
{
public:
void FromReal();
};
}
#endif
模式.cpp
#include "pattern.h"
#include "realdata.h"
#include <iostream>
namespace myprogram{
void Pattern::FromReal()
{
for (auto it=real_data.begin(); it !=real_data.end(); it++)
std::cout<<" my vector "<< *it <<" "<<std::endl;
}
}
真实数据.h
#ifndef REALDATA_H
#define REALDATA_H
#include<vector>
extern std::vector<double> real_data;
#endif
真实数据.cpp
#include "realdata.h"
std::vector<double> real_data{ 0., 0., 1.46, 1.51, 1.55, 1.58, 1.45, 1.48, 1.54, 1.54, 1.60, 1.56};
也不要忘记使用头卫
推荐阅读
- javascript - 如果 $http.get() 返回的数据不是 JSON 格式,它是一个普通的文本,如何处理?
- google-apps-script - 将电子邮件作为附件转发(通过应用程序脚本)会导致目标电子邮件收件箱中的附件为空
- angular2-forms - Angular2代码在文本框发生一些变化时如何将其反射回组件
- apache-spark - Spark kafka Streaming中的StreamingQueryException
- python - 无法使用 pynetdicom3 访问 PACS
- owl - OWL 2 如何表示等价类
- tableview - TableView 结果错误
- javascript - 在 Heroku 上测试 Postgre 数据库
- javascript - 我可以改进threejs以使一大组盒子在没有凸耳的情况下渲染得更快吗?
- java - 如何在 Kie 文件系统中重命名规则