ページ 1 / 1
クラス内のstatic変数のエラーについて(LNK2001&LNK2005)
Posted: 2015年8月28日(金) 00:55
by 苺カルピス
既出の可能性が高い質問ですがごめんなさい。。。
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()
{
~~~
}
どう改善すれば良いのか教えて頂きたいです><
Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)
Posted: 2015年8月28日(金) 02:40
by faserg1
こんにちは
In a.cpp don't use
<code>
int A::size;
</code>
You already declared "size" by including a.h
Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)
Posted: 2015年8月28日(金) 06:00
by 苺カルピス
ありがとうございます
解決できました!
We were able to solve
Thanks you! :)
追記:問題の起きたプログラムで、ヘッダではなくcppをインクルードしていました…
Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)
Posted: 2015年8月28日(金) 10:51
by みけCAT
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,
is needed in a.cpp or somewhere else.
c++ - What is the difference between a definition and a declaration? - Stack Overflow
sizeはa.hで宣言されているだけで定義されていないので、どこかに定義を書かないといけません。
Re: クラス内のstatic変数のエラーについて(LNK2001&LNK2005)
Posted: 2015年8月28日(金) 21:19
by faserg1
みけ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"