How to use a static method from another class without ::

时间:2018-04-20 00:49:00

标签: c++ static-methods

I am new to C++ and as a requirement for a program, I must use a pre-written main file. In that file, a method from another class is called as if it were defined in the main file. An example of this code is shown below.

main.cpp

#include <iostream>
#include "foo.h"
int main()
{
   cout << factorial(5);
   return 0;
}

foo.h

#ifndef FOO_H
#define FOO_H

class Foo
{
public:
    static int factorial(int);
}
#endif

foo.cpp

#include foo.h
int foo::factorial(int n)
{
    if (n == 0)
        return 1;
    else
        return n * factorial(n - 1);
}

The error that is produced is:

'factorial': identifier not found

If I were to replace cout << factorial(5) with cout << foo::factorial(5), then the program runs perfectly.

However, the main that was provided calls foo as if it was defined in main.cpp as shown in the first code block.

All the posts I found on similar topics were just "How to call methods of another class" answer: static method. But even with a static method, you must use foo::factorial(int) right? How do I call factorial(int) in main.cpp?

2 个答案:

答案 0 :(得分:1)

In C++, a separate include file (in this case "foo.h") is not required to map to a class called Foo. The included file can just declare the function factorial as a free function and define it in foo.cpp.

foo.hpp

#ifndef FOO_H
#define FOO_H

int factorial(int);

#endif

foo.cpp

#include "foo.h"

int factorial(int n)
{
    if (n == 0)
        return 1;
    else
        return n * factorial(n - 1);
}

答案 1 :(得分:1)

How to use a static method from another class without ::

You can't in this case. There are cases where this is possible where argument dependent lookup applies. ADL doesn't apply here, since the arguments are literals.

How do I call factorial(int) in main.cpp?

Using the scope resolution operator ::.

Your desire of calling without scope resolution, and the desire of using a static member function are in a conflict. You must choose one desire, and give up on it. If modifying main.cpp isn't an option, then you have to use a free function that is visible in the global namespace, instead of a member function.