gpt4 book ai didi

c++ - 静态方法初始化程序中的空 std::string

转载 作者:行者123 更新时间:2023-11-30 03:31:43 29 4
gpt4 key购买 nike

我正在使用静态方法来初始化类的常量字段。静态方法使用一些常量变量,这些变量存储在单独的头文件中。原始类型被正确传递给静态方法,但 std::strings 被传递为空。我不明白这是为什么。

在进行一些搜索之后,我偶然发现了一种叫做静态初始化程序失败的东西,但我无法解决这个问题,也无法确定是否应该责怪它。由于对象在全局范围内,问题是它在 std::string 类被“设置”之前被“设置”了吗?

我尝试复制下面的一个最小示例:

// File: settings.hpp
#include <string>
const std::string TERMINAL_STRING "Printing to the terminal";
const std::string FILE_STRING "Printing to a file";


// File: printer.hpp
#include <string>
#include <iostream>

class Printer
{
private:
const std::string welcomeMessage;
static std::string initWelcomeMessage(std::ostream&);

public:
Printer(std::ostream&);
}

extern Printer::print;


// File: printer.cpp
#include "settings.hpp"

std::string Printer::initWelcomeMessage(std::ostream &outStream)
{
if (&outStream == &std::cout)
{
return (TERMINAL_STRING);
}
else
{
return (FILE_STRING);
}
}

Printer::Printer(std::ostream &outStream) :
message(initWelcomeMessage(outStream)
{
outStream << welcomeMessage << std::endl;

return;
}


// File: main.cpp
#include "printer.hpp"

printer print(std::cout);

int main()
{
return (0);
}

非常感谢!

最佳答案

As the the object is in global scope, is the problem that it is being 'setup' before the std::string class has been 'setup'?

是的。

让您的字符串成为函数-静态,而不是通过引用从某个函数返回。

这是静态初始化顺序失败的传统修复方法。

关于c++ - 静态方法初始化程序中的空 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43988011/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com