繁体   English   中英

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

[英]How to implement static class member functions in *.cpp file?

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

所有static函数都总是inline吗?

这是。 关键是只在文件中使用static关键字,而不是在源文件中!

测试.hpp:

class A {
public:
    static int a(int i);  // use `static` here
};

测试.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;
}

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

尝试这个:

标头.hxx:

class CFoo
{
public: 
    static bool IsThisThingOn();
};

类.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();
}

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

在你的头文件中说foo.h

class Foo{
    public:
        static void someFunction(params..);
    // other stuff
}

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

#include "foo.h"

void Foo::someFunction(params..){
    // Implementation of someFunction
}

很重要

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

祝你好运

是的,您可以在 *.cpp 文件中定义静态成员函数。 如果您在标头中定义它,编译器将默认将其视为内联。 但是,这并不意味着静态成员函数的单独副本将存在于可执行文件中。 请关注这篇文章以了解更多信息: C++ 中的静态成员函数是否在多个翻译单元中复制?

@crobar,您说得对,缺少多文件示例,因此我决定分享以下内容,希望对其他人有所帮助:

::::::::::::::
main.cpp
::::::::::::::

#include <iostream>

#include "UseSomething.h"
#include "Something.h"

int main()
{
    UseSomething y;
    std::cout << y.getValue() << '\n';
}

::::::::::::::
Something.h
::::::::::::::

#ifndef SOMETHING_H_
#define SOMETHING_H_

class Something
{
private:
    static int s_value;
public:
    static int getValue() { return s_value; } // static member function
};
#endif

::::::::::::::
Something.cpp
::::::::::::::

#include "Something.h"

int Something::s_value = 1; // initializer

::::::::::::::
UseSomething.h
::::::::::::::

#ifndef USESOMETHING_H_
#define USESOMETHING_H_

class UseSomething
{
public:
    int getValue();
};

#endif

::::::::::::::
UseSomething.cpp
::::::::::::::

#include "UseSomething.h"
#include "Something.h"

int UseSomething::getValue()
{
    return(Something::getValue());
}

#include指令的字面意思是“将该文件中的所有数据复制到该位置”。 因此,当您包含头文件时,它以文本形式存在于代码文件中,并且其中的所有内容都将存在,当代码文件(现在称为编译单元翻译单元)是从预处理器模块移交给编译器模块。

这意味着您的静态成员函数的声明和定义一直在同一个文件中......

你当然可以。 我会说你应该。

本文可能有用:
http://www.learncpp.com/cpp-tutorial/812-static-member-functions/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM