从C ++中调用函数 [英] Calling Functions From Main in C++
问题描述
我想从Main.cpp调用我的Dijkstra()方法。
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;
}
它在我的头文件中的Alg类中是delcared:
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
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 c $ c>错误:不能调用成员函数'void Alg :: dijkstra()'没有对象,并调用它简单作为dijkstra()给出错误:'dijkstra'未在此范围中声明
。
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
.
以前,我在Main.cpp文件中定义了所有这些方法,这里: http://pastebin.com/67u9hGsL ),我现在缺少的东西,我已经分离它。 dijkstra()不需要输入,所有的其他功能都在头/ cpp文件与它。
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.
我如何成功地从主调用dijkstra()?
How can I successfully call dijkstra() from main?
推荐答案
您需要创建类的实例:
Alg a;
a.dijkstra();
或使 dijkstra
a static
方法:
static void dijkstra();
为了简化实现,我建议第一个选项。
for simplicity in your implementation I would recommend the first option.
这篇关于从C ++中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!