【问题标题】:"string temp(s);" where "s" is string“字符串温度;”其中“s”是字符串
【发布时间】:2020-04-29 00:46:41
【问题描述】:
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); 
} 

string 's' 是函数 printAllPermutations() 的形式参数。 我的疑问是: “string temp(s);”怎么样?当's'也是一个字符串并且'temp'是需要创建的新字符串时写?

【问题讨论】:

  • 我不明白你在问什么。请澄清你的问题。 sstd::stringtemp 是从 s 复制构造的 std::stringstd::string 有一个复制构造函数,它将数据从s 复制到temp。与将main() 中的s 复制到printAllPermutations() 中的s 相同

标签: c++ string syntax parameter-passing declaration


【解决方案1】:

声明

string temp(s);

direct initialization 中的temp。编译器将找到最匹配的构造函数重载,这将是string 的复制构造函数。这意味着你真的从s复制构造temp,它相当于

string temp = s;

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


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

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

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

printAllPermutations("AAB");

【讨论】:

    猜你喜欢
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    相关资源
    最近更新 更多