C++重写父类方法后,父类中同名的方法在子类中就无法被调用,回报这个问题:
java中是没有这个问题的,显然java设计者在设计的时候有意解决了这个问题。
C++实践代码:
#include <iostream>
using namespace std;
class Father{
private:
int father1;
public:
Father(){
this->father1 = 11;
//cout<< "无参构造器"<<endl;
}
virtual ~Father(){
//cout<< "Father析构函数"<<endl;
}
int getFather1(){
cout<< "Father:getFather1()"<<endl;
return father1;
}
int getFather1(int a){
cout<< "Father:getFather1(int a)"<<endl;
return father1;
}
};
class Son : public Father{
private:
int son1;
public:
Son(){
this->son1 = 11;
}
~Son(){
//cout<< "Son析构函数"<<endl;
}
int getSon1(){
return son1;
}
// 重写父类方法
int getFather1(){
cout<< "Son:getFather1()中调用重写的方法"<<endl;
return 100;
}
};
int main(){
cout << "方法重写实践:" << endl;
// 调用无参构造器
Son son;
// 调用son中重写的方法
cout << "son.getFather1():" << son.getFather1() << endl;
// 调用父类同名的方法 【报错】
cout << "son.getFather1(int a):" << son.getFather1(11) << endl;
cout << "方法重写实践 end." << endl;
return 0;
}
java实践代码:
package test.test;
class Father {
private int father1;
public Father() {
this.father1 = 11;
//cout<< "无参构造器"<<endl;
}
public int getFather1() {
System.out.println("Father:getFather1()");
return father1;
}
public int getFather1(int a) {
System.out.println("Father:getFather1(int a)");
return father1;
}
}
class Son extends Father {
private int son1;
public Son() {
this.son1 = 11;
}
public int getSon1() {
return son1;
}
// 重写父类方法
public int getFather1() {
System.out.println("Son:getFather1()中调用重写的方法");
return 100;
}
}
public class Main1 {
public static void main(String[] args) {
Son son = new Son();
// 调用son中重写的方法
son.getFather1();
// 调用父类被重写同名的方法,java中可以
son.getFather1(11);
System.out.println("end");
}
}
来源:oschina
链接:https://my.oschina.net/u/4307357/blog/4167585