* .cpp 파일에서 정적 클래스 멤버 함수를 구현하는 방법은 무엇입니까? * .cpp 파일에서 클래스 멤버

static헤더 파일에서 수행하는 대신 * .cpp 파일에서 클래스 멤버 함수 를 구현할 수 있습니까?

모든 static기능은 항상 inline있습니까?



답변

그것은.

test.hpp :

class A {
public:
    static int a(int i);
};

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;
}

항상 인라인은 아니지만 컴파일러가 만들 수 있습니다.


답변

이 시도:

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

C ++에서 정적 함수를 처리하는 방법에 대한 자세한 내용은 다음을 참조하십시오. C ++의 정적 멤버 함수가 여러 번역 단위로 복사됩니까?


답변

예, * .cpp 파일에서 정적 멤버 함수를 정의 할 수 있습니다. 헤더에서 정의하면 컴파일러는 기본적으로 인라인으로 처리합니다. 그러나 정적 멤버 함수의 별도 복사본이 실행 파일에 존재한다는 의미는 아닙니다. 이에 대해 자세히 알아 보려면이 게시물을 따르십시오.
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 키워드를 사용하지 않는지 확인하십시오.

행운을 빕니다


답변

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


답변

물론 넌 할 수있어. 당신이해야한다고 말하고 싶습니다.

이 기사가 유용 할 수 있습니다 :
http://www.learncpp.com/cpp-tutorial/812-static-member-functions/