Static Functions in C++

前端 未结 8 1300
野趣味
野趣味 2021-01-17 08:09

I\'ve read a few posts on here about static functions, but still am running into trouble with implementation.

I\'m writing a hardcoded example of Dijkstra\'s algorit

8条回答
  •  春和景丽
    2021-01-17 08:40

    Are you sure the function is supposed to be static?

    It looks as if you want just a function? in your header file:

    #ifndef DIJKSTRA_H
    #define DIJKSTRA_H
    void dijkstra(); 
    #endif
    

    in your cpp file

    void dijkstra() {
       /* do something */
    }
    

    in your main file:

    #include "yourcppfile.h"
    
    int main(int argc, char **argv) {
        dijkstra();
    }
    

    if you really want a static function you have to put it into a nested class:

    class Alg {
      public:
        static void dijkstra();
      /* some other class related stuff */
    }
    

    the implementation somewhere in a cpp file

    void Alg::dijkstra() {
      /* your code here */
    }
    

    and then in your cpp file where the main resides

    #include "your header file.h"
    
    int main(int argc, char **argv) {
      Alg::dijkstra();
    }
    

提交回复
热议问题