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.

Leave a Comment