staticヘッダーファイルではなく* .cppファイルにクラスメンバー関数を実装することは可能ですか?
すべてのstatic機能は常にinlineですか?
staticキーワードを繰り返さないでください。staticヘッダーファイルのクラス定義にのみキーワードを書き込む
staticヘッダーファイルではなく* .cppファイルにクラスメンバー関数を実装することは可能ですか?
すべてのstatic機能は常にinlineですか?
staticキーワードを繰り返さないでください。staticヘッダーファイルのクラス定義にのみキーワードを書き込む
回答:
そうです。
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;
}
それらは常にインラインであるとは限りませんが、コンパイラーはそれらを作成できます。
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 ++が静的関数を処理する方法の詳細については、次のWebサイトをご覧ください。
はい、*。cppファイルで静的メンバー関数を定義できます。ヘッダーで定義すると、コンパイラーはデフォルトでインラインとして扱います。ただし、静的メンバー関数の個別のコピーが実行可能ファイルに存在することを意味するものではありません。詳細については、この投稿に従ってください: C ++の静的メンバー関数は複数の翻訳単位でコピーされますか?
inlineか、templateまたはあなたがリンカから複数の定義のエラーを取得します。
ヘッダーファイルで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/