block中出現此種報錯: Incompatible block pointer types initializing 'float (^__strong)(float, float)' with an expression of type 'int (^)(float, float)'


當block(代碼塊)的返回值是float時,應注意的地方:定義的返回值類型一定要與return的返回值類型一樣

我們以兩個數的四則運算來舉例

在main.m文件中的四則運算中,我采用兩種返回值類型(int 與 float)相互對照。

 1 #import <Foundation/Foundation.h>
 2 void fun1(int(^block)(int a,int b)){  3     block(20,2);  4 }  5 
 6 void fun2(float(^block)(float a,float b)){  7     block(20.0,2.0);  8 }  9 
10 int main(int argc, const char * argv[]) { 11  @autoreleasepool { 12         
13     //block返回值為int類型
14         int(^myblock1)(int a,int b) = ^(int a,int b){ 15             int sum = a+b; 16             int dif = a-b; 17             int squ = a*b; 18             int div = a/b; 19             NSLog(@"和%d 差%d 積%d 商%d",sum,dif,squ,div); 20             return 0; 21  }; 22  fun1(myblock1); 23 
24     //block返回值為float類型
25         float (^myblock2)(float a,float b) = ^(float a,float b){ 26             float sum = a+b; 27             float dif = a-b; 28             float squ = a*b; 29             float div = a/b; 30             NSLog(@"和%.2f 差%f 積%f 商%f",sum,dif,squ,div); 31             return 0;    //此處有誤
32  }; 33  fun2(myblock2); 34  } 35     return 0; 36 }

 

分析:

 

初看這段程序,感覺還都挺對,如果在電腦上運行,返回值為“int”類型時,程序可以成功實現,但返回值類型為“float”類型時,在我們運行程序時會出現這樣的錯誤:

Incompatible block pointer types initializing 'float (^__strong)(float, float)' with an expression of type 'int (^)(float, float)'

我們要是知道“block”中的返回值的要求,我們就不難看出代碼的錯誤原因,在第二種方法,返回值為float類型,可“return”返回的值卻為“0”,(系統默認“0”為整形),前后矛盾,故而錯誤;並且我們可以通過驗證得知:return后的返回值為0.0或1.25等等float類型的數值時,計算機都會報錯,但當我們將return后的數值改為一個float類型的變量(如程序中的sum或dif等)或“0.0f”時,程序就是正確的,可以成功運行,原因就在於定義的返回值類型一定要與return的返回值類型一樣

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM