在C ++中从Main调用函数

时间:2013-12-03 23:21:19

标签: c++ compiler-errors dijkstra

我正在尝试从Main.cpp调用我的Dijkstra()方法。

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

int main(int argc, char **argv) { 

    Alg::dijkstra();
    return 1; 
}

我的头文件中的Alg类中显示了它:

#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

在我的Alg.cpp文件中实现:

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

将其称为Alg :: dijkstra()会给出error: cannot call member function ‘void Alg::dijkstra()’ without object,并将其称为dijkstra()给出error: ‘dijkstra’ was not declared in this scope

以前,我在Main.cpp文件中定义了所有这些方法并且它工作得很好(参见这里:http://pastebin.com/67u9hGsL),我现在在这里错过了一些我已经将它分开的东西。 dijkstra()不需要输入,所有其他函数都在header / cpp文件中。

如何从main成功调用dijkstra()?

1 个答案:

答案 0 :(得分:1)

你需要创建一个类的实例:

Alg a;
a.dijkstra();

或在课程中dijkstra static方法:

static void dijkstra();

为了简化您的实现,我建议您使用第一个选项。