How to implement static class member functions in *.cpp file?
It is. The key is to use the static
keyword only in the header file, not in the source file!
test.hpp:
class A {
public:
static int a(int i); // use `static` here
};
test.cpp:
#include <iostream>
#include "test.hpp"
int A::a(int i) { // do **not** use `static` here!
return i + 2;
}
using namespace std;
int main() {
cout << A::a(4) << endl;
}
They're not always inline, no, but the compiler can make them.
Try this:
header.hxx:
class CFoo
{
public:
static bool IsThisThingOn();
};
class.cxx:
#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
return true;
}
helper.hxx
class helper
{
public:
static void fn1 ()
{ /* defined in header itself */ }
/* fn2 defined in src file helper.cxx */
static void fn2();
};
helper.cxx
#include "helper.hxx"
void helper::fn2()
{
/* fn2 defined in helper.cxx */
/* do something */
}
A.cxx
#include "helper.hxx"
A::foo() {
helper::fn1();
helper::fn2();
}
To know more about how c++ handles static functions visit: Are static member functions in c++ copied in multiple translation units?