我猜想这段代码的最后两行应该可以编译。
#include "rapidjson/document.h"
int main(){
using namespace rapidjson ;
using namespace std ;
Document doc ;
Value obj(kObjectType) ;
obj.AddMember("key", "value", doc.GetAllocator()) ; //this compiles fine
obj.AddMember("key", string("value").c_str(), doc.GetAllocator()) ; //this does not compile!
}
不过,我的猜测是错误的。一行编译,另一行不编译。
AddMember
方法有多种变体,如记录here , 但除此之外...... 为什么返回 .c_str()
不等同于字符串文字?
我的理解是,在接受字符串文字的地方,您可以传递 string::c_str()
它应该有效。
PS:我正在使用 VC++ 2010 进行编译。
编辑:
缺少#include <string>
不是问题。它已包含在 document.h
中
这是错误:
error C2664: 'rapidjson::GenericValue<Encoding> &rapidjson::GenericValue<Encoding>::AddMember(rapidjson::GenericValue<Encoding> &,rapidjson::GenericValue<Encoding> &,Allocator &)'
: cannot convert parameter 1 from 'const char [4]' to 'rapidjson::GenericValue<Encoding> &'
with
[
Encoding=rapidjson::UTF8<>,
Allocator=rapidjson::MemoryPoolAllocator<>
]
and
[
Encoding=rapidjson::UTF8<>
]
编辑 2:
请忽略 .c_str()
的事实被称为时间值。这个例子只是为了显示编译错误。实际代码使用字符串变量。
编辑 3:
代码的替代版本:
string str("value") ;
obj.AddMember("key", "value", doc.GetAllocator()) ; //compiles
obj.AddMember("key", str, doc.GetAllocator()) ; // does not compile
obj.AddMember("key", str.c_str(), doc.GetAllocator()) ; // does not compile
最佳答案
std::string::c_str()
方法返回 char const*
.字符串文字的类型是 char const[N]
其中 N
是字符串中的字符数(包括空终止符)。相应地,c_str()
的结果可以不在所有可以使用字符串文字的地方使用!
如果您尝试调用的接口(interface)需要 char
,我会感到惊讶阵列,虽然。也就是说,在您的使用中它应该可以工作。您更有可能需要包括 <string>
.
关于c++ - 是否可以在需要字符串文字时使用 std::string::c_str() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41313720/