c++ - Multiple definition of a variable in C++ classes
问题描述
Assume these two cpp files:
0.cc
#include <iostream>
class test{
public:
int num = 5;
};
int main(){
test t;
return t.num;
}
1.cc
class test{
public:
int num = 6; // <-- note this has a different value.
};
We compile it with g++ 0.cc 1.cc
.
Initializing a member variable inside the class works since C++11. My question is how is it compiling whiteout a linker error? is it undefined behaviour? as we are breaking the one definition rule. If classes were not used this would generate a link error at compile time.
I know that defining a function within a class makes it inline so it would be ok to have multiple of them in different files, but not sure how multiple variables are ok?
解决方案
是的,这违反了One Definition Rule并且是Undefined Behavior。
推荐阅读
- javascript - Discord Bot 登录超过 1000 次
- r - 如何按列值计算同时存在的实体的最大数量?
- ios - 以编程方式选择 UICollectionViewCell
- rust - 为什么程序在明显的生命周期不匹配的情况下仍能编译?
- javascript - 在 Chrome 扩展程序中运行 tensorflow
- python - 在 google colab 上运行 python 文件时无法连接到 X 服务器
- python - 如何从枚举的元组列表中删除项目
- c# - 错误 ORA-00907 缺少右括号
- c# - C# XslCompiledTransform - 以 POCO 形式而不是 Html 输出
- apache-spark - 使用 PySpark 屏蔽信用卡号