我们可以将const char *分配给cpp中的字符串吗?

时间:2020-09-18 12:00:23

标签: c++

尽管我的编译器在将const char *分配给字符串时没有引发错误,但我想知道这种分配是否真的有效并且不会引发意外结果

string name;
const char* name2 = "ABCD";

name = name2;

2 个答案:

答案 0 :(得分:5)

您绝对可以。

select max(case when ObservationType = 'Clinical' then Observation end) as Clinical, max(case when ObservationType = 'Non-Clinical' then Observation end) as NonClinical from (select o.*, row_number() over (partition by ObservationType order by Observation) as seqnum from Observations o ) o group by seqnum order by seqnum; 旨在替换乏味且容易出错的C字符串std::string,因此要使其成为一个很好的替换/成功产品,它需要与const char*向后兼容

const char*调用name = name2;,因此,如果我们检查此操作符we can see(3)的operator=过载,则:

basic_string

此处basic_string& operator=( const CharT* s ); 的类型为CharT,因此您得到char

您将按照预期的方式进行操作,它将const char*指向的内容复制到const char*的内部缓冲区中:

将内容替换为以零结尾的字符串 由std::string指向,就像由s指向。

为了从assign(s, Traits::length(s))std::string,要走另一条路线,您需要在const char*对象上调用其方法c_str()。 / p>

答案 1 :(得分:3)

我想知道此作业是否真的有效

是的,有效的:

Name 2

注意function moveFiles() { const fileNames = ["Name 1", "Name 2", "Name 3", "Name 4", "Name 5"]; const pdfFolderId = "{source-folder-id}"; const usersParentFolderId = "{destination-folders-parent-id}"; let querySearch = "'" + pdfFolderId + "' in parents and ("; querySearch = fileNames.reduce((acc, fileName, index) => { if (index < fileNames.length - 1) { return acc + "title contains '" + fileName + "' or "; } else { return acc + "title contains '" + fileName + "')" } }, querySearch); const pdfFiles = DriveApp.searchFiles(querySearch); const usersParentFolder = DriveApp.getFolderById(usersParentFolderId); while (pdfFiles.hasNext()) { const file = pdfFiles.next(); const fileName = fileNames.find(fileName => file.getName().includes(fileName)); const userFolder = usersParentFolder.getFoldersByName(fileName).next(); // This assumes there is only one folder with this name (iterate if that's not the case) file.makeCopy(userFolder); } } 调用std :: string赋值运算符,此后两个变量完全独立,即,您可以随意更改string name; const char *name2 = "ABCD"; name = name2; ,而name = name2仍为const(即文字字符串) )。

相关问题