繁体   English   中英

矩形类的值显示为零

[英]value comes out as zero for rectangle class

  1. 当我编译它时,我总是得到零而不是值的任何建议?

  2. 这里的代码是关于我创建的一个简单的矩形类。

      #import <Foundation/Foundation.h> @interface Rectangle : NSObject { int width; int height; } @property int width, height; -(int) area; -(int) perimeter; -(void) setWH: (int) h: (int) w; @end #import "Rectangle.h" @implementation Rectangle @synthesize width, height; -(int) area { width*height; } -(int) perimeter { (width+height)*2; } -(void) setWH:(int)h :(int)w { w = width; h = height; } @end #import <Foundation/Foundation.h> #import "Rectangle.h" int main (int argc, const char*argv[]) { @autoreleasepool { Rectangle* r = [[Rectangle alloc]init]; [r setWH: 6:8]; NSLog(@"the width of the rectangle is %i and the hieght %i", r.width, r.height); NSLog(@"the area is %i and the perimeter is %i", [r perimeter], [r area]); } } 

您翻转了变量分配:

-(void) setWH:(int)h :(int)w {
       w = width;
       h = height;
 }

它应该是

-(void) setWH:(int)h :(int)w {
       width = w;
       height = h;
 }

一开始,我什至不了解它是如何编译的,因为没有self无法访问属性。 然后我看到了实例变量。

 @interface Rectangle : NSObject {
       int width;
       int height;
 }
 @property int width, height;

不要那样做 在现代的objective-c中,您根本不必为属性编写实例变量,它们将自动合成(通过您也不需要@synthesize方式)。 当然,您可以自由地编写它们(尤其是如果您开始学习OBjective-C时),但是最好为实例变量选择其他名称,因为否则会引起混淆。 一种标准做法是在属性名称前添加下划线。

//interface
@property (nonatomic, assign) int myProperty;

//implementation
@synthesize myProperty = _myProperty; //this will synthesize a getter, a setter and an instance variable "_myProperty"

通常,您应该更喜欢访问属性而不是实例变量,因为这样您就可以更改属性(存储数据的getters / setters /方法)实现,而无需更改其他任何东西。 因此,对于areaperimeter ,更好的解决方案是这样的(@PerfectPixel已经告诉您有关return因此请注意self )。

-(int) area {
    return self.width * self.height;
}
-(int) perimeter {
    return (self.width + self.height) * 2;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM