1
정적 메서드를 사용하여 클래스의 const 필드를 초기화하고 있습니다. 정적 메서드는 별도의 헤더 파일에 저장된 몇 가지 const 변수를 사용합니다. 기본 유형은 정적 메소드에 올바르게 전달되지만 std :: 문자열은 비워집니다. 나는 이것이 왜 있는지 이해할 수 없다.정적 메서드 초기화 프로그램에서 빈 std :: string
일부 검색을 수행 한 후에 정적 초기화 프로그램으로 인한 실패를 발견했지만 머리를 감싸는 데 문제가있어 비난하면 해결할 수 없습니다. 객체가 전역 범위에 있으므로 std :: string 클래스가 '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