不能分配 std::string
到 char[n]
(它会产生错误 error: incompatible types in assignment
)但通常,可以使用 strcopy
解决此问题(例如 first answer )。
我正在寻找类似的技巧来初始化 POD 中的 char[n]。这是我想要做的:
#include <string>
typedef struct{
char str[16];
} Pod;
int main() {
std::string s("does not compile");
Pod pod = {s};
}
此代码产生以下错误:error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘char’ in initialization
.
谢谢
编辑:我非常喜欢允许我对 Pod 和字段进行 const 的解决方案。另外,我想保留初始化器,现实世界中的字段多于一个。
编辑 2:提醒一下,以下代码可以工作,因此可以做一些小而漂亮的事情:Pod pod = {"this works"}
最佳答案
首先初始化一个Pod
对象,然后将字符串数据复制到该成员。
Pod pod;
assert(s.size()+1 <= sizeof(pod.str));
std::memcpy(&pod.str[0], s.data(), s.size()+1);
如果你想要一个 Pod const
,你可以利用 RVO:
Pod make_pod(std::string const& s) {
Pod pod;
assert(s.size()+1 <= sizeof(pod.str));
std::memcpy(&pod.str[0], s.c_str(), s.size()+1);
return pod;
}
Pod const pod = make_pod(s);
不过,如果您有很多成员,则手动初始化所有成员会有点烦人。如果数组在末尾,那就没那么糟糕了。
关于c++ - 将 std::string 分配给 char[n] 以进行 POD 初始化时如何解决不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17108921/