首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >"string temp(s);“其中"s”是字符串

问"string temp(s);“其中"s”是字符串
EN

Stack Overflow用户
提问于 2020-04-29 08:46:42
回答 1查看 316关注 0票数 0
代码语言:javascript
复制
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);“是怎么写的?

EN

回答 1

Stack Overflow用户

发布于 2020-04-29 08:53:37

这句话

代码语言:javascript
复制
string temp(s);

是temp的direct initialization。编译器将找到最匹配的构造函数重载,它将是string的复制构造函数。这意味着您实际上是从s复制构造temp,它等同于

代码语言:javascript
复制
string temp = s;

这意味着temp将成为s的副本。

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

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

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

代码语言:javascript
复制
printAllPermutations("AAB");
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61492387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档