我在这里读了一些关于静态函数的帖子,但是在实现时遇到了麻烦.
我正在编写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]我想在没有对象的情况下从main调用我的函数.当我在Main.cpp中拥有所有这些代码时,它工作得很好.将它拆分成单独的文件会导致错误
Main.cpp:15: error: ‘dijkstra’ was not declared in this scope
.我在搜索SE时遇到的帖子让我觉得要做到这一点,我需要将该方法设置为静态,但我仍然没有运气.我究竟做错了什么?
Main.cpp的:
#include#include "Alg.h" int main() { dijkstra(); return 0; } 编辑:添加完整的头文件,Alg.h:
#ifndef Alg_ #define Alg_ #include#include 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
您可以使用命名空间,而不是具有包含所有静态成员的类.
Alg.h:
namespace Alg { void dijkstra(); }
在Alg.cpp
namespace Alg { void dijkstra() { // ... your code } }
在main.cpp中
#include "Alg.h" int argc, char **argv) { Alg::dijkstra(); return 1; }
你确定该功能应该是静态的吗?
看起来好像只想要一个功能?在您的头文件中:
#ifndef DIJKSTRA_H #define DIJKSTRA_H void dijkstra(); #endif
在你的cpp文件中
void dijkstra() { /* do something */ }
在您的主文件中:
#include "yourcppfile.h" int main(int argc, char **argv) { dijkstra(); }
如果你真的想要一个静态函数,你必须把它放到一个嵌套类中:
class Alg { public: static void dijkstra(); /* some other class related stuff */ }
在cpp文件中的某处实现
void Alg::dijkstra() { /* your code here */ }
然后在主要驻留的cpp文件中
#include "your header file.h" int main(int argc, char **argv) { Alg::dijkstra(); }
你应该这样称呼它:
Alg::dijkstra();
限制
无法调用任何其他非静态的类函数.
无法访问非静态类数据成员.
new class()
当构造函数是私有/受保护时,可以实例化对象.例如工厂功能.