クラス内のstatic変数のエラーについて(LNK2001&LNK2005)

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
苺カルピス
記事: 2
登録日時: 11年前

クラス内のstatic変数のエラーについて(LNK2001&LNK2005)

#1

投稿記事 by 苺カルピス » 10年前

既出の可能性が高い質問ですがごめんなさい。。。

C++で書いたクラスのstatic変数の宣言の仕方に戸惑い、面倒臭い状態になっています。
症状としては、コンパイルするたびに変数の宣言を消す、書く、消す、書く(LNK2001未定義とLNK2005定義されています)
という状況になっています。。

プログラム

コード:

A.h

#pragma once

class A{
public:
    static void set(int _a){ size = _a; }
private:
    static int size;
};

A.cpp

#include "A.h"

//この部分をコメントアウトしたりしなかったり
int A::size;

main.cpp

#include "A.h"

int main()
{
 ~~~
}
どう改善すれば良いのか教えて頂きたいです><

faserg1
記事: 4
登録日時: 10年前

Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)

#2

投稿記事 by faserg1 » 10年前

こんにちは
In a.cpp don't use
<code>
int A::size;
</code>
You already declared "size" by including a.h

苺カルピス
記事: 2
登録日時: 11年前

Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)

#3

投稿記事 by 苺カルピス » 10年前

ありがとうございます
解決できました!
We were able to solve
Thanks you! :)

追記:問題の起きたプログラムで、ヘッダではなくcppをインクルードしていました…

アバター
みけCAT
記事: 6734
登録日時: 14年前
住所: 千葉県
連絡を取る:

Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)

#4

投稿記事 by みけCAT » 10年前

faserg1 さんが書きました:こんにちは
In a.cpp don't use
<code>
int A::size;
</code>
You already declared "size" by including a.h
I don't think that this is right.
"size" is declared but not defined in a.h
Therefore,

コード:

int A::size;
is needed in a.cpp or somewhere else.
c++ - What is the difference between a definition and a declaration? - Stack Overflow

sizeはa.hで宣言されているだけで定義されていないので、どこかに定義を書かないといけません。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

faserg1
記事: 4
登録日時: 10年前

Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)

#5

投稿記事 by faserg1 » 10年前

みけCAT さんが書きました:I don't think that this is right.
"size" is declared but not defined in a.h
いいえ、that's wrong think.
Also, problem already solved.
There we already declared AND defined A::size.
The problem, as I understand, was next – in main.cpp was included a.cpp
So, linker will say "A::size defined many times"

閉鎖

“C言語何でも質問掲示板” へ戻る