通过派生的指针调用基类函数 [英] Calling base class functions through derived pointers

查看:127
本文介绍了通过派生的指针调用基类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(目标C)如何在派生类中覆盖foo的情况下使用派生指针调用基类函数。基本等于此C ++代码

( Objective C ) How would I call a base class function using a derived pointer where foo is overridden in the derived class. Essentially the equivalent of this C++ code

base* b_ptr = 0 ;
derived* d_ptr = new derived() ;
d->base::foo() ;

我认为这应该很简单。我需要使用选择器吗?

I would think this should be fairly simple. Do I need to use a selector?

推荐答案

通常,您只能在类内部使用super关键字进行此操作

You would normally only do this from inside the class, using the super keyword

- (int)doSomething {
    NSLog(@"calling doSomething on base class");
    return [super doSomething];
}

但是,仍然可以使用运行时函数从类外部进行操作objc_msgSendSuper,但这有点棘手。

However, it's still possible to do it from outside the class using the runtime function objc_msgSendSuper, but it's a bit more tricky.

#import <objc/objc-runtime.h>

...

Derived *d = [Derived new];

// call doSomething on derived class
[d doSomething];

// call doSomething on base class
struct objc_super b = {
    .receiver = d,
    .class = class_getSuperclass([d class])
};
objc_msgSendSuper(&b, @selector(doSomething));
}

这篇关于通过派生的指针调用基类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆