首页 > 解决方案 > 如何在 Visual Studio 中修复“C2061 语法错误标识符“堆栈”?

问题描述

我在我的代码中使用堆栈,它显示了这个错误。其他问题说我有循环依赖,但我只有 1 个头文件

//function.h
#pragma once 

void dfs(int start, int goal, bool visited[], int **matrix, int size,
         bool &found, stack<int>& path);
//function.cpp
#include "function.h"
#include <iostream>
#include <stack>

using namespace std;

void dfs(int start, int goal, bool visited[], int **matrix, int size,
         bool &found, stack<int>& path)
{
    visited[start] = true;
    cout<<start<<" ";
    path.push(start);

    if (start == goal)
        found = true;

    for (int k = 0; k < size; k++)
    {
        if (visited[k] == false && matrix[start][k] && found == false )
            dfs(k,goal,visited,matrix,size,found,path);
        path.pop();
    }
}
//main.cpp
#include "function.h"
#include <iostream>
#include <fstream>
#include <stack>

using namespace std;
void main()
{
    stack<int> path;

    for(int i=0; i<N; i++)
        visit[i] = false; //init visit

    for(int i = 0; i < N; ++i)
        matrix[i] = new int[N]; // build rows

    for(int i = 0; i < N; ++i)
    {
        for(int j = 0; j < N; ++j)
        {
            fin>>matrix[i][j];
        }
    }

    dfs(start, end, visit, matrix, 5, found, path);    
}

它应该运行,但它一直给我这个语法错误:“错误 C2061:语法错误:标识符‘堆栈’”

标签: c++syntax

解决方案


你的头文件应该是这样的

//function.h
#pragma once 

#include <stack>

void dfs (int start, int goal, bool visited[], int **matrix, int size, bool 
&found, std::stack<int>& path);

您需要在看到函数原型#include <stack>之前。dfs

您应该完全限定类型名称stack(即std::stacknot stack),因为在头文件中这using namespace std;是一个非常糟糕的主意


推荐阅读