Static Functions in C++

前端 未结 8 1262
野趣味
野趣味 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:50

    In your header file Alg.h:

    #ifndef __ALG_H__
    #define __ALG_H__
    
    namespace Alg {
    
        void dijkstra();
    
    }
    
    #endif
    

    The include guards are necessary if you plan to include the header in more than one of your cpp files. It seems you would like to put the function in a namespace Alg, right?

    In Alg.cpp:

    #include "Alg.h"
    
    void Alg::dijkstra() { /* your implementation here */ }
    

    Then, in main.cpp you call it with full namespace qualification:

    #include "Alg.h"
    
    int main() {
    
        Alg::dijkstra();
    
    }
    

    If you just want to distribute your code over several files, I don't see why the function should be declared static.

    0 讨论(0)
  • 2021-01-17 08:53

    Now that we have the complete declaration of your class Arg, it feels like the singleton design pattern could be useful:

    http://en.wikipedia.org/wiki/Singleton_pattern

    0 讨论(0)
提交回复
热议问题