jah*_*haj 11
std :: string有一个构造函数,它接受一个const char*参数.当你向它传递NULL时,构造函数会崩溃,并且当你编写foo(NULL)时会隐式调用该构造函数.
我能想到的唯一解决方案是重载foo
void foo(const std::string& str)
{
// your function
}
void foo(const char* cstr)
{
if (cstr == NULL)
// do something
else
foo(std::string(cstr)); // call regular funciton
}
Run Code Online (Sandbox Code Playgroud)
你可以使用Boost.Optional.
#include <boost/optional.hpp>
#include <string>
using namespace std;
using namespace boost;
void func(optional<string>& s) {
if (s) { // implicitly converts to bool
// string passed in
cout << *s << endl; // use * to get to the string
} else {
// no string passed in
}
}
Run Code Online (Sandbox Code Playgroud)
用字符串调用它:
string s;
func(optional<string>(s));
Run Code Online (Sandbox Code Playgroud)
没有字符串:
func(optional<string>());
Run Code Online (Sandbox Code Playgroud)
Boost.Optional为您提供了一种类型安全的方法来获取可空值,而无需求助于指针及其相关问题.