B.h
ヘッダー ファイルでクラス B を定義しました。B には静的データ メンバーがあります。この静的データ メンバーは、ヘッダー ファイルでクラス B から定義しました。しかし、ビルドするとエラーが発生します。
main.obj : エラー LNK2005: "public: static class std::basic_string,class std::allocator > B::b" (?b@B@@2V?$basic_string@DU?$char_traits@D@std@@ V? $allocator@D@2@@std@@A) は既に B.obj で定義されています
致命的なエラー LNK1169: 1 つ以上の複数定義されたシンボルが見つかりました
B.h
:
#ifndef _B_H
#define _B_H
#include <string>
class B
{
public:
B();
~B();
static void showfunc();
static std::string b;
};
std::string B::b = "BBB";
#endif
B.cpp
:
#include <iostream>
#include <string>
#include "B.h"
using namespace std;
B::B()
{
}
B::~B()
{
}
void B::showfunc()
{
cout<<b<<endl;
}
// main.cpp
#include <iostream>
#include "B.h"
using namespace std;
int main()
{
B b_obj;
b_obj.showfunc();
return 0;
}