使用未声明的标识符“sum”

时间:2015-08-05 05:36:51

标签: objective-c function nslog

我第三次重复错误,但我找不到 什么是使用未声明的标识符的意思..

我在Objective-C

中编写了关于函数的程序
#import <Foundation/Foundation.h>

@interface Add:NSObject
/* method declaration */
 - (int)add:(int)a andNum2:(int)b;
@end

@implementation Add

/* method returning the max between two numbers */
 - (int)add:(int)a andNum2:(int)b{
/* local variable declaration */


int sum = a +b;
return sum;
}

@end

  NSLog(@"sum is : %d", sum);// error this line     
  return 0;
}

2 个答案:

答案 0 :(得分:0)

#import <Foundation/Foundation.h>
@interface Add:NSObject{

  int sum;//Declare sum as global variable to access in class
 }
  - (int)add:(int)a andNum2:(int)b;
 @end

 @implementation Add

   - (int)add:(int)a andNum2:(int)b{

   sum = a +b;//
   return sum;
}

@end

NSLog(@"sum is : %d", sum);//Now Access global variable with in class     

答案 1 :(得分:0)

这是确切的代码吗?如果是,则首先需要致电

NSLog(@"sum is : %d", sum);
return 0;

在某个功能中。

sum也是在add方法中声明的变量,因此不能在该函数之外使用。在sum下声明@interface Add:NSOBject以使用add方法。

如果您不想在add方法之外声明它,请更改行

NSLog(@"sum is : %d", sum);

NSLog(@"sum is : %d", [add:@(12) andNum2:@(13)]);

(注意:将12和13替换为任何其他数字或数字变量)

相关问题