从静态类调用函数

Calling a function from a static class

本文关键字:函数 调用 静态类      更新时间:2023-10-16

所以标题有点误导。但这正是我想要做的。我创建了一个小案例场景。这种情况在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(。

您需要:

  1. int someFunction();添加到main.cpp 的顶部

  2. int someFunction();添加到foo.h文件,然后在main.cpp 中添加#include "foo.h"