Static Functions in C++

2019-02-21 12:24发布

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 algorithm for finding the shortest path.

Declared in Alg.h:

static void dijkstra();

Defined in 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

I want to call my function from main without an object. When I had all of this code in Main.cpp, it worked perfectly. Splitting it up into separate files caused the error Main.cpp:15: error: ‘dijkstra’ was not declared in this scope.The posts I came across when searching SE gave me me the impression that to do this, I needed to make that method static, yet I still have no luck.

What am I doing wrong?

Main.cpp:

#include <iostream>
#include "Alg.h"

int main() { 

    dijkstra();
    return 0; 
}

Edit: Added full header file, 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

Original all-in-one working Main.cpp file: http://pastebin.com/67u9hGsL

8条回答
来,给爷笑一个
2楼-- · 2019-02-21 12:45

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();
}
查看更多
Bombasti
3楼-- · 2019-02-21 12:47

You can just use a namespace instead of having a class with all static members.

Alg.h:

namespace Alg
{
   void dijkstra();
}

and in Alg.cpp

namespace Alg
{
   void dijkstra()
   {
     // ... your code
   }
}

in main.cpp

#include "Alg.h"

int argc, char **argv)
{
  Alg::dijkstra();

  return 1;
}
查看更多
SAY GOODBYE
4楼-- · 2019-02-21 12:51

You should call it this way:

Alg::dijkstra();

Limitations

  • Can't call any other class functions that are not static.
  • Can't access non static class data members.
  • Can instantiate an object via new class() when constructor is private/protected. E.g. a factory function.
查看更多
Root(大扎)
5楼-- · 2019-02-21 12:51

If I remember right any 'static' function is limited to the module in which it is implemented. So, 'static' prevents using the function in another module.

查看更多
祖国的老花朵
6楼-- · 2019-02-21 12:59

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.

查看更多
倾城 Initia
7楼-- · 2019-02-21 13:03

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

查看更多
登录 后发表回答