使用函数调用初始化字符串成员 c++

Initialising a string member c++ with a functioncall

一个对象有一个字符串,需要构造

#include <string>

class SDLException
{
private:
    std::string what_str;
public:
    SDLException(const std::string &msg);
    ~SDLException(void);
};

该字符串具有我需要考虑的隐藏依赖项 (SDL_GetError())。我可以在函数中构造字符串。但我不知道如何使用该函数的 return 值来初始化字符串成员。

#include "SDLException.hpp"

#include <sstream>
#include <string>
#include <SDL.h>

static void buildSTR(const std::string &msg)
{
    std::ostringstream stream;
    stream << msg << " error: " << SDL_GetError();
    std::string str =  stream.str();
    //if i return a string here it would be out of scope when i use it
}

SDLException::SDLException(const std::string &msg)
    : what_str(/*i want to initialise this string here*/)
{}

SDLException::~SDLException(void){}

如何以最少的开销初始化成员 what_strwhat_str的内容应该等于str的内容。

您的 buildSTR() 函数应该 return 一个字符串:

static std::string buildSTR(const std::string &msg)
{
    std::ostringstream stream;
    stream << msg << " error: " << SDL_GetError();
    return stream.str();
}

那么在这里使用就没有问题了:

SDLException::SDLException(const std::string &msg)
    : what_str(buildSTR(msg))
{ }

或者,您可以省略 sstream 包含并简单地使用字符串连接,因为 std::string 有一个运算符重载以允许连接 const char*.例如:

SDLException::SDLException(const std::string &msg)
    : what_str(msg + " error: " + SDL_GetError())
{ }

你快到了。将 BuildSTR 更改为 return 字符串和 return 来自 BuildSTR 的字符串。然后调用buildSTR(msg)初始化what_str.