如何使用派生类对象访问派生类中具有相同名称的基类方法 [英] How Can i access base class method having same name in derived class using derived class object

查看:106
本文介绍了如何使用派生类对象访问派生类中具有相同名称的基类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Base
{
    public void Method()
    {
        // ...
    }
}

class Derived : Base
{
    public void Method()
    {
        // ...
    }
}

main()
{

}





所以在main函数中如何访问基类方法在派生类中使用派生类对象具有相同的名称。



so in main function How Can i access base class method having same name in derived class using derived class object.

推荐答案

base.method();



似乎我需要添加更多内容,但没有什么可说的了。
base.method();

Seems I need to add more content, but there's nothing more to say.


Delphi的技巧过去只是简单地将其转换回来到它的基类并从那里打电话。这对于被某些组件隐藏的属性非常有用。



你可以尝试一下:)



The trick with Delphi used to be to simply cast it back to it's base class and call from there. This worked exceptionally well for properties that where hidden by certain components.

You could give it a try :)

(base)derivedObject.method();





祝你好运!



good luck!


你不能!如果一个类继承自基类并重写基类的某些方法,则假定新类扩展了基类:基类方法知道如何处理基类,但这不能成为继承类的有效操作!



你可以做的是:



You cannot! If a class inherit from a base class and override some methods of the base class, it's assumed that the new class extends the base class: the base class method knows how to deal with the base class, but that could not be a valid operation to be done on the inherited class!

What you can do is this:

class Base
{
   public virtual void Method()
   {
      // Do something specific to Base class
      ...
   }
}

class Derived : Base
{
   public override void Method()
   {
      // This will call Base.Method() ...
      base.Method();

      // ... and now we extend the functionalities of Method() by doing something more specific to Derived class
      ...
   }
}


这篇关于如何使用派生类对象访问派生类中具有相同名称的基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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