如何将多维数组传递给C++中的头文件

How to pass multi-dimensional array to header file in C++

本文关键字:C++ 文件 数组      更新时间:2023-10-16

我正在尝试使用多维数组。我的目标是为我的矩阵函数提供一个单独的文件,但是我在设置 V 的值时遇到问题。

错误 : ‘V’ was not declared in this scope由于此错误陈述非常广泛,因此我在搜索中找不到令人满意的答案。

这就是我想要实现的。

主.cpp

#include <bits/stdc++.h> 
using namespace std;
#include "prims.h"
int main()  
{   int V = 5;
    int graph[V][V] = { {... },  
                        {... },  
                        {... },   
                        {... },   
                        {... } };    
    func1(graph);
    func2(graph); 
    return 0;  
}

普里姆斯·

#ifndef PRIMS_H
#define PRIMS_H
#include <bits/stdc++.h> 
using namespace std;
int func1(int graph[V][V]);
int func2(int graph[V][V]);
#endif

普瑞姆.cpp

#include <bits/stdc++.h> 
using namespace std;
#include "prims.h"
int func1(int graph[V][V])  
{  
  // function
} 
int func2(int graph[V][V])  
{  
  // function
}

如果需要更多澄清,请在下面发表评论。谢谢。

由于你想从 main 设置值,一种替代方法是在 main 中将V声明为全局变量,在 prims.h 中声明为 extern const int,以便它在 prmis 中也可见.cpp。

普里姆斯·

extern const int V;

主.cpp

const int V = 5; //declared as global in main
int main()  
{  
   /* */
}