2011-06-01 38 views
4
#include <iostream> 
#include <string> 
#include <algorithm>  
int main() 
{ 
std::string str1 = "good", str2 = "luck"; 
swap(str1,str2); /*Line A*/ 
int x = 5, y= 3; 
swap(x,y); /*Line B*/ 
} 

如果我評論行B代碼編譯(http://www.ideone.com/hbHwf)而註釋行A代碼無法編譯(http ://www.ideone.com/odHka),我收到以下錯誤:交換失敗的情況下int和字符串的情況下工作

error: ‘swap’ was not declared in this scope 

爲什麼不讓我在第一種情況下得到任何錯誤?因爲Argument dependent lookup

回答

3

你沒有資格swap;傳遞因爲ADLstd::string對象時它的工作原理,但int不駐留在命名空間std則必須完全限定通話:

std::swap(x, y); 

或使用使用聲明:

using std::swap; 
swap(x, y); 
2

字符串都在std :: namespace,因此編譯器在那裏查找字符串的swap()。整數不是,所以沒有。你想:

std::swap(x,y); 
1

在這兩種情況下,你應該使用std::swap()代替swap()

相關問題