关于继承中出现的名称屏蔽(方法隐藏)对比C++和Java的不同处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/swgshj/article/details/81633171

C++代码

C++中子类“重载了”父类中的方法会导致父类的方法在该子类中被隐藏,即子类无法再调用父类中的void print(int a)和void print(char a[])。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

class Base
{
    public:
        void print(int a) { printf("Base::print(int)\n"); }
        void print(char a[]) { printf("Base::print(char[])\n"); }

        void print2(int a) { printf("Base::print2(int)\n"); }
};

class Inherit: public Base
{
    public:

        void print(Base &b) { printf("Inherit::print(Base)\n"); }
};

int main(int argc, char **argv)
{


    Base b;
    Inherit i;
    char a[10] = "hello";

    b.print(10);
    b.print(a);

    //i.print(10);  //error: the base class member function will be hidden, derived class need to override all the base class member function which want to use in derived class
    //i.print(a);   // same with above
    i.print(b);

    i.print2(10);
    return 0;
}

Java代码(代码片段来源于Java编程思想第4版)

Java不会屏蔽父类的同名方法,子类可以调用自己重载的方法void doh(Milhouse m)和可以调用父类的char doh(char c)和float doh(float f)

//: reusing/Hide.java
// Overloading a base-class method name in a derived
// class does not hide the base-class versions.
import static net.mindview.util.Print.*;

class Homer {
  char doh(char c) {
    print("doh(char)");
    return 'd';
  }
  float doh(float f) {
    print("doh(float)");
    return 1.0f;
  }
}

class Milhouse {}

class Bart extends Homer {
  void doh(Milhouse m) {
    print("doh(Milhouse)");
  }
}

public class Hide {
  public static void main(String[] args) {
    Bart b = new Bart();
    b.doh(1);
    b.doh('x');
    b.doh(1.0f);
    b.doh(new Milhouse());
  }
} /* Output:
doh(float)
doh(char)
doh(float)
doh(Milhouse)
*///:~

Java可以通过@Override防止误重载(编译器发现会报错)

//: reusing/Lisa.java
// {CompileTimeError} (Won't compile)

class Lisa extends Homer {
  @Override void doh(Milhouse m) {
    System.out.println("doh(Milhouse)");
  }
} ///:~

猜你喜欢

转载自blog.csdn.net/swgshj/article/details/81633171
今日推荐