C++ 中的静态函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20362973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Static Functions in C++
提问by Ladybro
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. When I had all of this code in Main.cpp, it worked perfectly. 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 调用我的函数。当我在 Main.cpp 中拥有所有这些代码时,它工作得很好。将其拆分为单独的文件会导致错误Main.cpp:15: error: ‘dijkstra' was not declared in this scope
。我在搜索 SE 时遇到的帖子给我的印象是,要做到这一点,我需要将该方法设为静态,但我仍然没有运气。
What am I doing wrong?
我究竟做错了什么?
Main.cpp:
主.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
回答by egur
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. E.g. a factory function.
- 不能调用任何其他非静态的类函数。
- 无法访问非静态类数据成员。
new class()
当构造函数是私有/受保护时,可以通过实例化对象。例如工厂函数。
回答by user3053099
You can just use a namespace instead of having a class with all static members.
您可以只使用命名空间而不是具有所有静态成员的类。
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;
}
回答by Alex
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();
}
回答by VladimirM
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' 阻止在另一个模块中使用该函数。
回答by KeithSmith
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. This will allow Alg.o to contain global symbols that main
can refer to and the linker can link.
删除static
Alg.cpp 和头文件中的第一行。这将允许 Alg.o 包含main
可以引用和链接器可以链接的全局符号。
You still need to call Alg::dijkstra()
as was stated by @egur.
您仍然需要Alg::dijkstra()
按照@egur 的说明进行调用。
After this you may still get errors. The way you are using Alg:: is more like a namespace
than a 'class' definition.
在此之后,您可能仍会遇到错误。您使用 Alg:: 的方式更像是 a 而namespace
不是“类”定义。
回答by blackbird
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. It seems you would like to put the function in a namespace Alg
, right?
如果您计划在多个 cpp 文件中包含标头,则包含保护是必要的。您似乎想将该函数放在 namespace 中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
。
回答by blackbird
Now that we have the complete declaration of your class Arg
, it feels like the singleton design pattern could be useful:
现在我们有了 class 的完整声明Arg
,感觉单例设计模式可能很有用:
回答by Prashant Kumar
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. Make a new source file with this in it:
获取您的多合一源文件并删除该main
功能。用它创建一个新的源文件:
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. You will get a duplicate symbol _main
error if you forgot to remove the main from the algorithm file.
main
上面没有加这个文件的多合一 cpp应该编译在一起,并为您提供与以前相同的结果,就像对我一样。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. It solves the compile-time error though.
我在这里的回答没有涉及头文件的良好做法,也就是说,您可能希望将这些函数声明包含在.h
文件中。不过它解决了编译时错误。
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. This can be bewildering, and it proves to be exactly that for a language with as much colorful history as C++. Take a look herefor book suggestions.
您可能想找一本好书来帮助您了解 C++ 的一些机制,其中程序上下文(在语言意义上)可以改变关键字的含义。这可能令人眼花缭乱,事实证明,对于像 C++ 一样拥有丰富多彩历史的语言来说,这正是如此。看看这里的书籍建议。