在C++中从Main调用函数
Calling Functions From Main in C++
我正试图从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();
为了简化您的实现,我推荐第一个选项。
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?