1. 程式人生 > >no suitable ctr exists to convert from 'int' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char> >

no suitable ctr exists to convert from 'int' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char> >

賦值 數字 數組 table col 初始 大小 遍歷 one

技術分享
 1 int xfun(int *a,int n)
 2 {
 3     int x = *a;//a的類型是int *,a+1跳動一個int的長度
 4     for (int *pa = a + 1; pa < a + n; pa++)//指向同一個類型的指針比較大小,相減是兩者之間的元素個數
 5     {
 6         //string s = pa - a;// string接受const char*的單參構造函數不是explicit的,但編譯器不能把int轉換為string類型
 7         decltype(pa - a) t;
 8         int arr[3
][4]; 9 decltype(arr) Type; 10 float f = pa - a;//因為float是四個字節,有效數字為6為,int轉換為float可能丟失精度 11 cout << *pa << endl; 12 if (*pa > x) 13 x = *pa; 14 } 15 return x; 16 } 17 int main() 18 { 19 int x[5] = { 23, 46, 78, 55, 16 }; 20 cout<<xfun(x, 5
); 21 }
View Code

以上代碼可討論幾個問題,記錄在下面。這段代碼的功能是找出數組中的最大值,用x記錄比較過程,x初始為a[0],從第二個元素開始比較,比x大,x值就更新,遍歷完數組,x就是最大的。

技術分享

1、std::string編譯器是不認識的,只認識int,float,int*等類型,string在編譯器裏的類型是std::basic_string<char,std::char_traits<char>,std::allocator<char> > ;

2、pa(搜狗中文輸入狀態下輸入“pa”,按下Enter是選中英文字符,按下空格鍵是選中“怕”,按下shift是選中英文字符,且切換到英文狀態 ),如下圖所示:

技術分享

3、string的單參ctr接受const char*,但不接受int,這個ctr不是explicit的,不能把int隱式轉換為string

4、怎麽獲得兩個指針相減的結果類型?即獲取表達式的類型,用decltype,不計算表達式的值,只得到類型,如圖:

技術分享

指針相減的類型為ptrdiff_t ,這是一個signed int,如上圖所示

技術分享

arr的類型是二維數組,arr+1是跳一個二維數組的長度,即12個int大小

5、int和float在32位下為4個bytes,float有效數字為6位,int轉換為float可能會丟失精度,warning C4244: ‘initializing‘ : conversion from ‘int‘ to ‘float‘, possible loss of data;int賦值給double,後者為8個字節,足夠裝下所有的int,warning就會消失了。

6、pa<pa+n,pa滿足循環條件的最大值為pa+n-1,pa+0就是pa,指向a[1],pa+n-1指向數組的最後一個元素

no suitable ctr exists to convert from 'int' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char> >