我在这里读到了一些有关静态函数的帖子,但是在实现上仍然遇到了问题。
我正在编写Dijkstra算法的硬编码示例,用于找到最短路径。
在Alg.h中声明:
static void dijkstra();
在 Alg.cpp 中定义:
static void Alg::dijkstra() {
//Create Map
Initialize();
//Loop to pass through grid multiple times
for(int i=0; i<5; i++)
{
current=1;
while(current!=6)
{
//Iterate through and update distances/predecessors
//For loop to go through columns, while current iterates rows
for(int j=1; j<7; j++)
{
//Check if distance from current to this node is less than
//distance already stored in d[j] + weight of edge
if(distanceArray[current][j]+d[current]<d[j])
{
//Update distance
d[j] = distanceArray[current][j]+d[current];
//Update predecessor
p[j] = current;
}
}
//Go to next row in distanceArray[][]
current++;
} //End while
} //End for
output();
} //End Dijkstras
我希望从主函数中无需对象调用我的函数。当我把所有代码放在Main.cpp中时,它能够完美运行。但是将其拆分为单独的文件导致错误
Main.cpp:15: error: ‘dijkstra’ was not declared in this scope
。搜索SE时看到的帖子让我觉得,要做到这一点,我需要将该方法设为静态,但我仍然没有成功。我做错了什么?
Main.cpp:
#include <iostream>
#include "Alg.h"
int main() {
dijkstra();
return 0;
}
编辑:添加完整的头文件Alg.h:
#ifndef Alg_
#define Alg_
#include <iostream>
#include <stack>
using namespace std;
class Alg
{
public:
void tracePath(int x);
void output();
void printArray();
void Initialize();
static void dijkstra();
int current, mindex;
int distanceArray[7][7]; //2D array to hold the distances from each point to all others
int d[6]; //Single distance array from source to points
int p[6]; //Array to keep predecessors
int copyD[6]; //Copy of d[] used for sorting purposes in tracePath()
int order[6]; //Contains the order of the nodes path lengths in ascending order
}; //End alg class
#endif
原始的全功能工作的Main.cpp文件:http://pastebin.com/67u9hGsL
dijkstra
应该是一个类静态成员? - CB Baileystatic void Alg::dijkstra() {
将立即在Alg.cpp
中触发编译错误。然而,你报告了一个完全不同的错误。并且你声称这段代码在main.cpp
中“工作”。这意味着你发布了虚假的代码。你的说法是不现实的。请发布真实的代码。 - AnT stands with RussiaAlg
是什么?它是一个类吗?还是一个命名空间? - AnT stands with RussiaAlg
,也没有static
。 - AnT stands with Russia