Joh*_*nes 0 c++ initialization member
对象有一个字符串,需要构造.
#include <string>
class SDLException
{
private:
std::string what_str;
public:
SDLException(const std::string &msg);
~SDLException(void);
};
Run Code Online (Sandbox Code Playgroud)
该字符串具有隐藏的依赖关系,我需要考虑(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){}
Run Code Online (Sandbox Code Playgroud)
如何what_str以最小的开销初始化成员?内容what_str应该等于的内容str.
你的buildSTR()函数应该返回一个字符串:
static std::string buildSTR(const std::string &msg)
{
std::ostringstream stream;
stream << msg << " error: " << SDL_GetError();
return stream.str();
}
Run Code Online (Sandbox Code Playgroud)
这里使用它没有问题:
SDLException::SDLException(const std::string &msg)
: what_str(buildSTR(msg))
{ }
Run Code Online (Sandbox Code Playgroud)
或者,您可以省略sstreaminclude并简单地使用字符串连接,因为std::string有一个运算符重载以允许连接const char*.例如:
SDLException::SDLException(const std::string &msg)
: what_str(msg + " error: " + SDL_GetError())
{ }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |