简体   繁体   English

C ++中的静态函数

[英]Static Functions in C++

I've read a few posts on here about static functions, but still am running into trouble with implementation. 我在这里读了一些关于静态函数的帖子,但是在实现时遇到了麻烦。

I'm writing a hardcoded example of Dijkstra's algorithm for finding the shortest path. 我正在编写Dijkstra算法的硬编码示例,用于查找最短路径。

Declared in Alg.h: 在Alg.h中声明:

static void dijkstra();

Defined in Alg.cpp: 在Alg.cpp中定义:

static void Alg::dijkstra() { 

//Create Map
Initialize();

//Loop to pass through grid multiple times
for(int i=0; i<5; i++)
{   
    current=1;  
    while(current!=6)
    {
        //Iterate through and update distances/predecessors
        //For loop to 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])
            {
                //Update distance
                d[j] = distanceArray[current][j]+d[current];
                //Update predecessor
                p[j] = current;
            }    
        }
        //Go to next row in distanceArray[][]
        current++;
    } //End while


} //End for

output();
} //End Dijkstras

I want to call my function from main without an object . 我想在没有对象的情况下从main调用我的函数。 When I had all of this code in Main.cpp, it worked perfectly. 当我在Main.cpp中拥有所有这些代码时,它工作得很好。 Splitting it up into separate files caused the error Main.cpp:15: error: 'dijkstra' was not declared in this scope .The posts I came across when searching SE gave me me the impression that to do this, I needed to make that method static, yet I still have no luck. 将它拆分成单独的文件导致错误Main.cpp:15: error: 'dijkstra' was not declared in this scope 。我在搜索SE时遇到的帖子给了我的印象,要做到这一点,我需要做到方法静态,但我仍然没有运气。

What am I doing wrong? 我究竟做错了什么?

Main.cpp: Main.cpp的:

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

int main() { 

    dijkstra();
    return 0; 
}

Edit: Added full header file, Alg.h: 编辑:添加完整的头文件,Alg.h:

#ifndef Alg_
#define Alg_

#include <iostream>
#include <stack>

using namespace std;

class Alg
{
    public:
        void tracePath(int x);
        void output();
        void printArray();
        void Initialize();
        static 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

Original all-in-one working Main.cpp file: http://pastebin.com/67u9hGsL 原始的一体化工作Main.cpp文件: http//pastebin.com/67u9hGsL

You should call it this way: 你应该这样称呼它:

Alg::dijkstra();

Limitations 限制

  • Can't call any other class functions that are not static. 无法调用任何其他非静态的类函数。
  • Can't access non static class data members. 无法访问非静态类数据成员。
  • Can instantiate an object via new class() when constructor is private/protected. 当构造函数为private / protected时,可以通过new class()实例化对象。 Eg a factory function. 例如工厂功能。

You can just use a namespace instead of having a class with all static members. 您可以使用命名空间,而不是具有包含所有静态成员的类。

Alg.h: Alg.h:

namespace Alg
{
   void dijkstra();
}

and in Alg.cpp 在Alg.cpp

namespace Alg
{
   void dijkstra()
   {
     // ... your code
   }
}

in main.cpp 在main.cpp中

#include "Alg.h"

int argc, char **argv)
{
  Alg::dijkstra();

  return 1;
}

Are you sure the function is supposed to be static? 你确定该功能应该是静态的吗?

It looks as if you want just a function? 看起来好像只想要一个功能? in your header file: 在您的头文件中:

#ifndef DIJKSTRA_H
#define DIJKSTRA_H
void dijkstra(); 
#endif

in your cpp file 在你的cpp文件中

void dijkstra() {
   /* do something */
}

in your main file: 在您的主文件中:

#include "yourcppfile.h"

int main(int argc, char **argv) {
    dijkstra();
}

if you really want a static function you have to put it into a nested class: 如果你真的想要一个静态函数,你必须把它放到一个嵌套类中:

class Alg {
  public:
    static void dijkstra();
  /* some other class related stuff */
}

the implementation somewhere in a cpp file 在cpp文件中的某处实现

void Alg::dijkstra() {
  /* your code here */
}

and then in your cpp file where the main resides 然后在主要驻留的cpp文件中

#include "your header file.h"

int main(int argc, char **argv) {
  Alg::dijkstra();
}

If I remember right any 'static' function is limited to the module in which it is implemented. 如果我没记错,任何“静态”功能仅限于实现它的模块。 So, 'static' prevents using the function in another module. 因此,'static'阻止在另一个模块中使用该函数。

You are confusing the 'static' keyword for local functions, with the 'static' keyword used in a class to make a function a class function and not an object function. 你在混淆局部函数的'static'关键字,在类中使用'static'关键字使函数成为类函数而不是对象函数。

Remove static the first line of Alg.cpp and in the header file. 删除static Alg.cpp的第一行和头文件。 This will allow Alg.o to contain global symbols that main can refer to and the linker can link. 这将允许Alg.o包含main可以引用的全局符号,链接器可以链接。

You still need to call Alg::dijkstra() as was stated by @egur. 你仍然需要像@egur所说的那样调用Alg::dijkstra()

After this you may still get errors. 在此之后,您可能仍会收到错误。 The way you are using Alg:: is more like a namespace than a 'class' definition. 你使用Alg ::的方式更像是namespace不是'类'定义。

In your header file Alg.h : 在头文件Alg.h

#ifndef __ALG_H__
#define __ALG_H__

namespace Alg {

    void dijkstra();

}

#endif

The include guards are necessary if you plan to include the header in more than one of your cpp files. 如果您计划在多个cpp文件中包含标头,则必须使用包含保护。 It seems you would like to put the function in a namespace Alg , right? 看来你想把这个函数放在命名空间Alg ,对吧?

In Alg.cpp: 在Alg.cpp中:

#include "Alg.h"

void Alg::dijkstra() { /* your implementation here */ }

Then, in main.cpp you call it with full namespace qualification: 然后,在main.cpp中,使用完整的命名空间限定来调用它:

#include "Alg.h"

int main() {

    Alg::dijkstra();

}

If you just want to distribute your code over several files, I don't see why the function should be declared static . 如果您只想将代码分发给多个文件,我不明白为什么该函数应该声明为static

Now that we have the complete declaration of your class Arg , it feels like the singleton design pattern could be useful: 现在我们已经完成了类Arg的完整声明,感觉单例设计模式可能很有用:

http://en.wikipedia.org/wiki/Singleton_pattern http://en.wikipedia.org/wiki/Singleton_pattern

The key here is the 'dijkstra' was not declared in this scope error. 这里的关键是'dijkstra' was not declared in this scope错误。

Take your all-in-one source file and remove the main function. 获取一体化源文件并删除main函数。 Make a new source file with this in it: 用它来创建一个新的源文件:

void dijkstra();
void output();

int main(int argc, char *argv[]) {
    dijkstra();
    output();
    return 0;
}

The all-in-one cpp without a main plus this file above should compile together and give you the same result as before with one source, as it does for me. 上面没有main加上这个文件的一体化cpp应该一起编译,并为你提供与之前相同的结果,就像我一样。 You will get a duplicate symbol _main error if you forgot to remove the main from the algorithm file. 如果您忘记从算法文件中删除main,则会出现duplicate symbol _main错误。

No static needed. 不需要static


My answer here fails to touch on good practices on header files, that is, you would want to include those function declarations in a .h file. 我在这里的答案没有涉及头文件的良好实践,也就是说,您希望将这些函数声明包含在.h文件中。 It solves the compile-time error though. 它解决了编译时错误。

You may want to find a good book to help you through some of the machinery of C++, where program context (in a linguistic sense) can change the meaning of keywords. 您可能希望找到一本好书来帮助您完成C ++的一些机制,其中程序上下文(在语言意义上)可以改变关键字的含义。 This can be bewildering, and it proves to be exactly that for a language with as much colorful history as C++. 这可能是令人困惑的,并且它证明了对于具有与C ++一样丰富多彩的历史的语言。 Take a look here for book suggestions. 看看这里的书籍建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM