Java关键字super和C++中virtual的区别

2 篇文章 0 订阅

Java关键字super的使用
在java中派生类继承基类,如果想访问派生类和基类的方法,我们可以重写父类的方法,并且通过super调用父类的方法就可以实现访问父类的方法
代码实例

public class People {

    public void eat(){
        System.out.println(" People eat()");
    }
}

public class man extends People{

    @Override
    public void eat() {
       super.eat();
        System.out.println(" man eat()");
    }
}
public static void main(String[] args) throws Exception {

    People man = new man();
    man.eat();
}

日志打印

 People eat()
 man eat()

C++中virtual的使用
在C++中,如果派生类继承基类都有相同的方法,如果我们想执行派生类的方法,那么我们就需要在基类中用virtual关键字来修饰该方法,如果不用virtual关键字来修饰该方法,那么就会执行基类中的方法
代码实例

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

class Human {
private:
	int a;
public:
	virtual void eating(void) { cout<<"Human eating(void)"<<endl; }
	virtual ~Human() { cout<<"~Human()"<<endl; }
	
};

class Englishman : public Human {
public:
	void eating(void) { cout<<"Englishman eating(void) "<<endl; }
	virtual ~Englishman() { cout<<"~Englishman()"<<endl; }

};


int main(int argc, char **argv)
{
	
	Englishman e;
	Human *h = &e;
	h->eating();

	return 0;
}



日志打印

Englishman eating(void)
~Englishman()
~Human()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值