1
私はクラスのconstフィールドを初期化する静的メソッドを使用しています。静的メソッドは、別のヘッダーファイルに格納されているいくつかのconst変数を使用します。プリミティブ型は静的メソッドに正しく渡されますが、std :: stringsは空に渡されます。なぜこれが理解できないのですか?静的メソッドの初期化子で空のstd :: string
いくつかの検索をした後、私は静的な初期化子の失敗と遭遇しましたが、私の頭をラップするのに問題があります。オブジェクトがグローバルスコープにあるので、std :: stringクラスが 'setup'される前に 'setup'されているという問題がありますか?
私は以下の最小限の例を再現しようとしている:
// 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);
}
どうもありがとうございました!
ご確認いただきありがとうございます。 – user7119460