如何在*.cpp文件中实现静态类成员函数?

113 c++

是否可以static在*.cpp文件中实现类成员函数而不是在头文件中执行它?

所有static功能总是inline吗?

Cro*_*yer 143

它是.

test.hpp:

class A {
public:
    static int a(int i);
};
Run Code Online (Sandbox Code Playgroud)

TEST.CPP:

#include <iostream>
#include "test.hpp"


int A::a(int i) {
    return i + 2;
}

using namespace std;
int main() {
    cout << A::a(4) << endl;
}
Run Code Online (Sandbox Code Playgroud)

它们并不总是内联的,不是,但编译器可以制作它们.


pau*_*cam 47

试试这个:

header.hxx:

class CFoo
{
public: 
    static bool IsThisThingOn();
};
Run Code Online (Sandbox Code Playgroud)

class.cxx:

#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)


小智 9

helper.hxx

class helper
{
 public: 
   static void fn1 () 
   { /* defined in header itself */ }

   /* fn2 defined in src file helper.cxx */
   static void fn2(); 
};
Run Code Online (Sandbox Code Playgroud)

helper.cxx

#include "helper.hxx"
void helper::fn2()
{
  /* fn2 defined in helper.cxx */
  /* do something */
}
Run Code Online (Sandbox Code Playgroud)

A.cxx

#include "helper.hxx"
A::foo() {
  helper::fn1(); 
  helper::fn2();
}
Run Code Online (Sandbox Code Playgroud)

要了解有关c ++如何处理静态函数的更多信息,请访问:c ++中的静态成员函数是否在多个翻译单元中复制?


Mr.*_*Jha 6

在你的头文件中输入foo.h

class Foo{
    public:
        static void someFunction(params..);
    // other stuff
}
Run Code Online (Sandbox Code Playgroud)

在你的实现文件中说foo.cpp

#include "foo.h"

void Foo::someFunction(params..){
    // Implementation of someFunction
}
Run Code Online (Sandbox Code Playgroud)

很重要

只需确保在实现文件中实现静态函数时,不要在方法签名中使用 static 关键字。

祝你好运