C 加关于在头文件或源文件中定义静态数据成员
C plus plus about defining static data member in header file or source file
我在头文件中定义了一个类B B.h
。B 具有静态数据成员。我在头文件中从类 B 中定义了这个静态数据成员。但是当我构建它时,发生了错误。
main.obj : 错误 LNK2005: "公共: 静态类 标准::basic_string,类 std::分配器> 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;
}
您已在头文件中定义了一个静态变量。仅当静态文件只包含一次时,这才有效!但是您包含它两次(主要.cpp和 B.cpp)。将以下行移动到 B.cpp它就可以工作了:
std::string B::b = "BBB";
您需要
将b
的定义移动到.cpp
文件中。
我在头文件中从类 B 中定义了这个静态数据成员。但是当我构建它时,发生了错误。
那就干脆不要那样做!
不要在标头中定义静态成员。您需要将定义引入到#include
标头的每个 TU 中。
而是在一个 TU 中定义它们;最简单的方法是在 .cpp 文件中。
// B.h
#ifndef _B_H
#define _B_H
#include <string>
class B {
public:
B();
~B();
static void showfunc();
static std::string b;
};
#endif
//B.cpp #include <iostream>
#include <string>
#include "MyHeader1.h"
using namespace std;
B::B(){}
B::~B(){}
void B::showfunc(){
cout<<b<<endl;
}
// main.cpp
#include <iostream>
#include "MyHeader1.h"
using namespace std;
std::string B::b = "BBB";
int main(){
B b_obj;
b_obj.showfunc();
return 0;
}
这里是您的解决方案
如果您在 hader 文件中编写了定义,则此定义将在包含此标头的每个对象模块中复制。因此,链接器将不知道要使用哪个定义以及这些定义是否等效。
相关文章:
- 使用多个源文件时对类成员函数的未定义引用
- C++,是否有可能/如何定义在.h和.cpp源文件中调用函数的类构造函数
- C++ 在一个源文件中使用另一个源文件中的矢量定义
- C++:实现定义了可接受的物理源文件字符
- 有没有办法声明一个公共静态常量,该常量将使用 constexpr 在源文件中定义(有什么区别)?
- 如何在源文件中定义模板函数
- 避免对仅在源文件中定义的类发出弱 vtable 警告
- 从源文件中定义的类访问标头中定义的类的私有变量
- 使用TSHARK C 源文件时未定义的参考在添加所需库后剖析消息
- 在源文件中定义链接选项C++
- 如何将包含多个.cpp源文件的文件夹导入Eclipse项目中,每个源文件都有一个main()定义
- 我应该在源文件之间共享的常量的定义中添加关键字"extern"吗
- 在源文件中定义 const 数组
- 从C源文件调用C++源文件中定义的全局函数
- 源文件中定义静态原子变量不好
- 如何在源文件中定义类并将其声明在标题文件中(而不必使用`class :: method'语法定义类方法)
- 在源文件中定义数组,然后在其他源文件中使用它
- 在C中如何在命令行中定义所有不知道宏(在源文件/标头文件中使用)
- 如何从另一个.cpp源文件调用main.cpp中定义的方法
- C++ - 定义类模板(头文件/源文件)