c++ - C ++中的简单属性访问不起作用
问题描述
这些文件中的每一个都应位于同一目录中,并且可以逐字复制。我有一个非常奇怪的属性访问问题,我不了解我目前对 C++ 的了解。
主文件
#include "someclass.hpp"
SomeClass d = SomeClass();
int main(int argc, const char * argv[])
{
SomeClass c = SomeClass();
return 0;
}
某类.hpp
#ifndef someclass_hpp
#define someclass_hpp
class SomeClass
{
public:
SomeClass();
};
#endif /* someclass_hpp */
某类.cpp
#include "someclass.hpp"
#include <iostream>
std::string s = "hi";
SomeClass::SomeClass()
{
std::cout << "\"" + s + "\"" << std::endl;
}
安慰
$ g++ main.cpp someclass.hpp someclass.cpp
$ ./a.out
""
"hi"
我进行了一个相当大的项目并删除了所有内容,直到留下了这个非常简单的错误,我已经盯着它看了一个小时,无法绕开我的脑袋。这是一个简单的问题,我没有考虑正确的方法吗?据我所知,代码应该输出“hi”两次,是什么让 a 的初始化上下文与b有什么不同?
I currently have the solution down to "don't init variables outside of methods", but I'm still curious why this occurs.
解决方案
Keep in mind that both, std::string s = "hi";
and SomeClass d =
SomeClass();
are initialized globally and the order of initialization isn't
guaranteed. This can also lead to undefined behavior.
FYI: your example is crashed on the latest Fedora.
UPD As @davidbak correctly mentioned, my answer is about the order of global initialization in different compilation units.
推荐阅读
- postgresql - 如何通过命令提示符备份或导出 Postgres 数据库
- mysql - 字符串操作 W3Resources
- html - 图像悬停样式无法实现
- javascript - 使用 Javascript 和单选按钮显示文本文件
- javascript - 在段落标记内插入选定文本的 HTML 标记
- ruby-on-rails - 共享点提供商在 Visual Studio 2017 中托管应用程序以在组织级别发布
- java - Spring RequestMapping 不会在 .jsp 请求上触发
- ios - 在使用 swift 的 iOS 中,如何创建一个始终位于整个应用程序顶部的可拖动和浮动 UIView
- python - Jupyter notebook 多窗口输出
- ios - 用动画在 UIImageView 上显示多个图像