在我的程序中,我有一个类,比如 ClassA
。我想创建一个派生类,比如 ClassB
。我的程序具有返回 ClassA
实例的函数,在某些情况下我想使用这些返回来创建 ClassB
的实例。进行简单的向下转换不会导致任何编译器错误,但会出现运行时错误。这似乎与转换指针与对象的问题有关——无论如何,从我读过的内容来看,这是错误的事情在这种情况下要做。
然后我尝试模仿 C++ 的复制构造函数,但复制的变量超出范围或被释放,再次导致运行时错误。
我也考虑过使用类别,但这似乎不合适,原因有二:
- 首先也是最重要的,我不能添加带有类别的新类(class)成员,如果我不能这样做,事情会变得有点复杂。
- 据我所知,通过类别添加的方法对类的所有实例都可用。严格来说,虽然这不是一个问题,但我不太满意,因为我想添加的方法的某些方面会在一般设置中中断;也就是说,它们在某种程度上特定于我需要对这些类型的对象执行的操作。
我仍在学习 Objective-C。我知道论坛中有一些类似的问题,但答案要么导致分类和死胡同,要么毫无帮助,所以我觉得我应该简单地重新发布。
最佳答案
In my program I have a class, say ClassA. I'd like to create a derived class, say ClassB.
@class MONClassA;
@interface MONClassB : MONClassA
{
int anotherVariable;
}
//...
- (id)initWithMONClassA:(MONClassA *)classA anotherVariable:(int)anotherVar;
@end
My program has functions returning instances of ClassA and in certain cases I'd like to use these returns to create an instance of ClassB.
与您在 C++ 中执行此操作的方式相同(听起来这就是您的背景),使用新实例提升类型:
//...
MONClassA * a = SomeLibFunction();
MONClassB * b = [[MONClassB alloc] initWithMONClassA:a anotherVariable:???];
//...
Doing the naive downcasting doesn't lead to any compiler errors, but runtime errors creep in. This seems to be related to issues about casting pointers vs. objects -- at any rate, from what I've read, this was the wrong thing to do in this case.
正确 - 这是错误的做法。
I then attempted to mimic the copy-constructors of C++, but variables that were copied passed out of scope or were released, leading again to run-time errors.
查看上面的实现,了解如何在 objc 中提升类型。这当然假设您还将为初始化定义一个适当的实现(相当于您的 cpp 构造函数和复制构造函数)。
I also considered using categories but this doesn't seem right...
那么你的直觉可能是对的。此语言功能经常被滥用。
关于Objective-C继承;从父类向下转型/复制到派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169412/