使用functioncall初始化字符串成员c ++

时间:2015-02-23 21:28:48

标签: c++ initialization member

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

#include <string>

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

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

#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的内容相同。

2 个答案:

答案 0 :(得分:5)

你的buildSTR()函数应该返回一个字符串:

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())
{ }

答案 1 :(得分:0)

你几乎就在那里。更改BuildSTR以返回一个字符串并从BuildSTR返回您的str。然后调用buildSTR(msg)初始化what_str。