从静态类调用函数
Calling a function from a static class
所以标题有点误导。但这正是我想要做的。我创建了一个小案例场景。这种情况在Visual Studio中有效,但在Mingw上尝试时出错。情况是这样的。我正试图从驻留在不同cpp文件中的静态方法调用cpp文件内的函数。这只是一个粗略的代码,它将使我的观点得到理解。
文件:foo.h
#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED
#include <iostream>
struct foo
{
int someMethod();
};
#endif // FOO_H_INCLUDED
文件:foo.cpp
#include "foo.h"
int someFunction()
{
std::cout << "SomeFunction";
return 0;
}
int foo::someMethod()
{
std::cout << "foo called";
return 0;
}
文件:main.cpp
void myfunction()
{
}
struct bar
{
static void somebar()
{
someFunction(); //error: 'someFunction' was not declared in this scope
myfunction(); //OK
}
};
int main()
{
}
我的问题是为什么我在someFunction()上出错;这是我的编译器输出
g++.exe -Wall -std=c++98 -g -std=c++11 -I......mingw64include -c C:UserspeeruTestCodeBlocksfoo.cpp -o objDebugfoo.o
C:UserspeeruTestCodeBlocksfoo.cpp: In function 'int someFunction()':
C:UserspeeruTestCodeBlocksfoo.cpp:6:1: warning: no return statement in function returning non-void [-Wreturn-type]
}
^
C:UserspeeruTestCodeBlocksfoo.cpp: In member function 'int foo::someMethod()':
C:UserspeeruTestCodeBlocksfoo.cpp:11:1: warning: no return statement in function returning non-void [-Wreturn-type]
}
^
g++.exe -Wall -std=c++98 -g -std=c++11 -I......mingw64include -c C:UserspeeruTestCodeBlocksmain.cpp -o objDebugmain.o
C:UserspeeruTestCodeBlocksmain.cpp: In static member function 'static void bar::somebar()':
C:UserspeeruTestCodeBlocksmain.cpp:14:21: error: 'someFunction' was not declared in this scope
someFunction();
^
Process terminated with status 1 (0 minute(s), 0 second(s))
1 error(s), 2 warning(s) (0 minute(s), 0 second(s))
有什么建议吗?
someFunction
没有在main.cpp
中声明,只是在一个单独的翻译单元foo.cpp
中声明。函数在使用前需要声明。
在main.cpp
中添加声明,或在两者中添加标头:
int someFunction();
正如其他警告所说,您还需要从声称返回int
的函数中返回一些内容。
您也必须为main.cpp
中的函数提供声明,相应地修改foo.h
标头:
#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED
#include <iostream>
int someFunction();
struct foo
{
int someMethod();
};
#endif // FOO_H_INCLUDED
并在CCD_ 9中添加CCD_。
我不知道为什么MSVC++编译时没有抱怨。
方法someFunction
和所有其他方法都声明为返回类型int
。因此,在函数的末尾添加return 0
,或者将它们声明为void。并且不能从静态函数调用非静态函数。
您在foo.cpp中声明了someFunction(),但在main.cpp中没有。main.cpp在编译时,它不知道someFunction(。
您需要:
将
int someFunction();
添加到main.cpp 的顶部将
int someFunction();
添加到foo.h文件,然后在main.cpp 中添加#include "foo.h"
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销