【发布时间】:2011-06-27 12:41:30
【问题描述】:
我有一个Matrix-Class 派生自Vector-Class,为了获得额外的功能和更好的使用,我有一个派生自Vector 类的Vector3-Class。我现在的问题是Vector-class 实现了一个函数,例如+normalizeVector:,它返回一个新分配的Vector-instance。子类Vector3 应该继承这两个函数,但是继承会导致函数原型返回Vector-instance 而不是Vector3-instance。这就是继承的工作原理,但是有一个好的做法来解决这个问题吗?一个天真的解决方案是创建 Vector3 也是一个新类,它是 NSObject 的子类,但我希望 Vector- 和 Vector3-instances 可以轻松交互。
这里是一个代码示例:
@interface Vector : NSObject {
....
}
+(Vector*) normalizeVector:(Vector*)v; //returns a new allocated Vector-instance
-(Vector*) normalize; //normalizes itself and returns itself
-(Vector*) otherFunction;
@end
@interface Vector3 : Vector {
}
-(Vector3*) specialFunction;
@end
该代码的用法:
Vector3 *v3 = ...;
[[v3 normalize] specialFunction]; //Compiler gives me a warning because Vector has no specialFunction. Cast would help
[[Vector3 normalizeVector:v3] specialFunction]; //Compiler gives me a warning and during runtime it will crash because a `Vector` doesn't implement specialFunction
对Vector3 的强制转换会有所帮助,但使用起来并不好,而且静态函数+normalizeVector: 也会失败,因为在该静态函数中分配了Vector-instance,而没有指针强制转换帮助。
有什么想法吗?或其他方法/其他建模?
编辑: 由Vector3 继承的静态函数 normalizeVector 的代码:
@implementation Vector
...
+(Vector*) normalizeVector:(Vector *)v
{
unsigned int dim = vector_max(v.cols, v.rows);
Vector *res = [[[Vector alloc]initAsColumnVectorWithDim:dim] autorelease];
[Vector normalizeVector:v destination:res]; // this does only the logic: calc length and divide each component by the len and store at the vector passed to destination
return res;
}
@end
【问题讨论】:
-
显示 +normalizeVector 的代码:
-
@fakeAccount22:看看我的编辑
标签: objective-c xcode inheritance