"string temp(s);" 其中"s"是字符串


void printAllPermutations(string s) 
{ 
// Sorting String 
string temp(s); 
sort(temp.begin(), temp.end()); 
// Print first permutation 
cout << temp << endl; 
// Finding the total permutations 
int total = calculateTotal(temp, temp.length()); 
for (int i = 1; i < total; i++)  
{ 
nextPermutation(temp); 
} 
} 
int main()  
{ 
string s = "AAB"; 
printAllPermutations(s); 
} 

字符串's'是函数printAllPermutations((的一个形式参数。我的怀疑是:当"s"也是一个字符串,而"temp"是需要创建的新字符串时,如何编写"string temp(s(;"?

语句

string temp(s);

是CCD_ 1的直接初始化。编译器将找到最匹配的构造函数重载,它将是string的复制构造函数。这意味着您真正从s复制构造temp,它相当于

string temp = s;

这意味着temp将是s的副本。


考虑到printAllPermutations函数按值接受参数s,您实际上并不需要temp变量,您可以直接处理temp0,因为它将是您在调用printAllPermutations时使用的字符串的副本。

通过使用temp,您最初有三个字符串副本:main函数中用于printAllPermutations调用的原始字符串;s中的副本;以及temp中的副本。

实际上,main函数中也不需要对象s,您可以在函数调用中直接传递文本字符串"AAB"

printAllPermutations("AAB");

相关内容

最新更新