【发布时间】:2020-11-25 18:41:03
【问题描述】:
我有以下三个文件:
测试.h
#pragma once
#include <iostream>
class Test{
public:
Test(std::string string);
};
test.cpp
#include "test.h"
#include <map>
std::map<int, int> HEY = {
{1, 45},
{2, 2}
};
Test::Test(std::string string) {
std::cout << "hello" << std::endl;
if (HEY.empty()) {
std::cout << "Is empty!" << std::endl;
} else {
std::cout << "Not empty!" << std::endl;
}
}
来源.cpp
#include "test.h"
Test test("hey");
int main() {
return 0;
}
预期输出
hello
Not empty!
实际输出
hello
Is empty!
当我在 Microsoft Visual Studio 2019 中运行程序时,我希望“不是空的!”要输出,表明映射HEY 中有元素,因为它是用两对初始化的。然而输出实际上是“是空的!”。
我不想在 main 函数中初始化 test,因为我希望它是一个全局变量,尽管我注意到当我在 main 函数中创建它时,我得到了正确的输出。
我做错了什么?这是编译器/链接器错误吗?我没有适当地声明HEY 地图吗? test 必须是一个全局变量。
【问题讨论】:
-
这被称为静态初始化命令惨败。 SO上有很多帖子显示了处理它的不同方法。我留给你决定使用哪一个。
标签: c++ class visual-studio-2019 stdmap