在C++中从Main调用函数

Calling Functions From Main in C++

本文关键字:调用 函数 Main 中从 C++      更新时间:2023-10-16

我正试图从Main.cpp.调用我的Dijkstra()方法

#include <iostream>
#include "Alg.h"
int main(int argc, char **argv) { 
    Alg::dijkstra();
    return 1; 
}

它在我的头文件中的Alg类中被delcare:

#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()不需要输入,它的所有其他函数都在它的头/cpp文件中。

如何从main成功调用dijkstra()

您需要创建类的实例:

Alg a;
a.dijkstra();

或者使dijkstra成为类中的static方法:

static void dijkstra();

为了简化您的实现,我推荐第一个选项。