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:找到一个或多个多重定义的符号
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;
}