问题
I'm trying to call my Dijkstra() method from Main.cpp.
#include <iostream>
#include "Alg.h"
int main(int argc, char **argv) {
Alg::dijkstra();
return 1;
}
It is delcared in my Alg class in my header file:
#ifndef Alg_
#define Alg_
#include <iostream>
#include <stack>
using namespace std;
class Alg
{
public:
void tracePath(int x);
void output();
void printArray();
void Initialize();
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
And implemented in my Alg.cpp file:
void Alg::dijkstra() {
//Create Map
Initialize();
for(int i=0; i<5; i++)
{
current=1;
while(current!=6)
{
//Iterate through and update distances/predecessors
//For loopt 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])
{
//cout<<"Previous distance to "<<j<<" was "<<d[j]<<" from "<<p[j]<<endl;
//cout<<"New smaller distance is "<<distanceArray[current][j]+d[current]<<" from "<<current<<endl;
//Update distance
d[j] = distanceArray[current][j]+d[current];
//Update p
p[j] = current;
}
}
//Go to next row in distanceArray[][]
current++;
} //End while
} //End for
//printArray();
output();
} //End Dijkstras
Calling it as Alg::dijkstra() gives error: cannot call member function ‘void Alg::dijkstra()’ without object
, and calling it simply as dijkstra() gives error: ‘dijkstra’ was not declared in this scope
.
Previously, I had all of these methods defined in my Main.cpp file and it worked just fine (see here: http://pastebin.com/67u9hGsL), I'm missing something here now that I've separated it. dijkstra() needs no input, and all of it's other functions are in the header/cpp files with it.
How can I successfully call dijkstra() from main?
回答1:
You need to make an instance of the class:
Alg a;
a.dijkstra();
or make dijkstra
a static
method in the class:
static void dijkstra();
for simplicity in your implementation I would recommend the first option.
来源:https://stackoverflow.com/questions/20363761/calling-functions-from-main-in-c