[英]passing a vector of structs into a function
在程序中,头文件中定义了以下结构:
\\structs.h
#include <vector>
using std::vector;
using namespace std;
struct cell
{
double x;
vector<int> nn;
};
在单独的源文件中,我定义了函数:
\\functions.cpp
# define _CRT_SECURE_NO_DEPRECATE
# include <stdio.h>
# include <iostream>
# include <math.h>
# include <vector>
# include "structs.h"
using namespace std;
void initial_position(vector<cell>& cluster, int n)
{
cell tmp;
for (int i = 0; i < n; i++)
{
tmp.x = 1;
cluster.push_back(tmp);
}
}
带有头文件:
//functions.h
# include <vector>
using std::vector;
void initial_position(vector<cell>& cluster, int n);
我希望在主脚本中调用此函数:
//main.cpp
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <vector>
#include "functions.h"
#include "structs.h"
using namespace std;
int main()
{
vector <cell> cluster;
int n = 100;
initial_position(cluster,n);
return 0;
}
但出现以下错误:
functions.h(4):错误C2065:'cell':未声明的标识符
functions.h(4):错误C2923:'std :: vector':'cell'不是参数'_Ty'的有效模板类型参数
functions.h(4):错误C3203:'分配器':未专用的类模板不能用作模板参数'_Alloc'的模板参数,应为实型
main.cpp(14):错误C2664:'void initial_position(std :: vector&)':无法将参数1从'std :: vector>'转换为'std :: vector&'
错误的根源是什么? 一切似乎都定义清楚。
放
#include "structs.h"
进入functions.h并使用include-guards保护structs.h和functions.h
#pragma once
如果可供使用的话。
加
#include "structs.h"
进入functions.h中,因为在functions.h中,编译器不知道什么是单元格。
只是交换
#include "functions.h"
#include "structs.h"
同
#include "structs.h"
#include "functions.h"
由于cell是在structs.h中声明的,而在functions.h中是必需的
或者更好的是,在functions.h中包含structs.h
您也不应在标题中使用命名空间std,这是一种不好的做法。 它可能会导致难以发现的错误,例如, 为什么“使用命名空间标准”被认为是不良做法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.