gpt4 book ai didi

ios - 这个多态性的例子是错误的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:02:38 26 4
gpt4 key购买 nike

我正在尝试了解多态性,我的理解是这意味着您可以在多个类中使用相同的方法,并且在运行时将根据调用它的对象的类型调用正确的版本.

下面这个例子说明:

http://www.tutorialspoint.com/objective_c/objective_c_polymorphism.htm

“Objective-C 多态性意味着对成员函数的调用将导致执行不同的函数,具体取决于调用该函数的对象的类型。”

在这个例子中,正方形和长方形都是形状的子类,它们都实现了自己的 calculateArea 方法,我假设正是这个方法被用来演示多态性概念。他们在 Square 对象上调用“calculateArea”并调用 squares calculateArea 方法,然后在 Rectangle 对象上调用“caculateArea”并调用 rectangles 的 calculateArea 方法。它不可能那么简单,当然这是显而易见的,square 甚至不知道矩形“calculateArea”,它在一个完全不同的类中,所以不可能对使用哪个版本的方法感到困惑。

我错过了什么?

最佳答案

你是对的,那个例子并没有说明多态性。这就是他们编写示例的方式。

#import <Foundation/Foundation.h>
//PARENT CLASS FOR ALL THE SHAPES
@interface Shape : NSObject
{
CGFloat area;
}
- (void)printArea;
- (void)calculateArea;
@end

@implementation Shape
- (void)printArea{
NSLog(@"The area is %f", area);
}
- (void)calculateArea
{
NSLog(@"Subclass should implement this %s", __PRETTY_FUNCTION__);
}
@end

@interface Square : Shape
{
CGFloat length;
}
- (id)initWithSide:(CGFloat)side;
@end

@implementation Square

- (id)initWithSide:(CGFloat)side{
length = side;
return self;
}
- (void)calculateArea{
area = length * length;
}
- (void)printArea{
NSLog(@"The area of square is %f", area);
}
@end

@interface Rectangle : Shape
{
CGFloat length;
CGFloat breadth;
}
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
@end

@implementation Rectangle

- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth{
length = rLength;
breadth = rBreadth;
return self;
}
- (void)calculateArea{
area = length * breadth;
}

@end


int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Shape *shape_s = [[Square alloc]initWithSide:10.0];
[shape_s calculateArea]; //shape_s of type Shape, but calling calculateArea will call the
//method defined inside Square
[shape_s printArea]; //printArea implemented inside Square class will be called

Shape *shape_rect = [[Rectangle alloc]
initWithLength:10.0 andBreadth:5.0];
[shape_rect calculateArea]; //Even though shape_rect is type Shape, Rectangle's
//calculateArea will be called.
[shape_rect printArea]; //printArea of Rectangle will be called.
[pool drain];
return 0;
}

关于ios - 这个多态性的例子是错误的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20286872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com