首页 > 解决方案 > 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.

标签: c++

解决方案


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.


推荐阅读