java和c++在override上的差别
我们先来看这样几段java代码:
A.java:
package org.linhao;public class A { public A() { // TODO Auto-generated constructor stub super(); } public void foo() { System.out.println("A::foo()"); }}
B.java:
package org.linhao;public class B extends A { public B() { // TODO Auto-generated constructor stub super(); } public void foo() { System.out.println("B::foo()"); }}
Test.java:
package org.linhao;public class Test { public static void main(String[] args) { // TODO Auto-generated method stub A a = new B(); a.foo(); }}
输出:
B::foo()
我们再来看一段c++代码:
// test.cpp : Defines the entry point for the console application.//#include "stdafx.h"class A{public: void foo() { printf("A::foo()\n"); }};class B : public A{public: void foo() { printf("B::foo()\n"); }};int main(int argc, char* argv[]){ A *pA = new B(); pA->foo(); return 0;}
输出:
A::foo()
从输出可以看出,java中类B的foo方法override了父类A的foo方法,但是c++中却没有。
这是为什么呢?在java中,只要子类的方法名、参数名、参数个数和返回类型和父类的方法相同,则认为子类的方法override了父类的方法。但是在c++中不是,除了要满足上述条件,还必须加上virtual关键字去告诉编译器这个方法是要override的。
改正后的c++代码如下:
// test.cpp : Defines the entry point for the console application.//#include "stdafx.h"class A{public: virtual void foo() { printf("A::foo()\n"); }};class B : public A{public: virtual void foo() { printf("B::foo()\n"); }};int main(int argc, char* argv[]){ A *pA = new B(); pA->foo(); return 0;}
输出:
B::foo()