C/C++与Java函数重载区别!

#include <iostream> using namespace std; class Base { public: virtual void fn(int x) { cout << "In Base class, int x = " << x << endl; } }; class SubClass : public Base { public: // 函数的重载,这样的重载方式,在Java中能行,在C/C++中却不行 virtual void fn(float x) { cout << "In SubClass, float x = " << x << endl; } }; void test(Base& b) { int i = 1; b.fn(i); float f = 2.0; b.fn(f); } int main() { Base bc; SubClass sc; cout << "Calling test(bc)/n"; test(bc); cout << "Calling test(sc)/n"; test(sc); return 0; }

 

 

Calling test(bc)
In Base class, int x = 1
In Base class, int x = 2
Calling test(sc)
In Base class, int x = 1
In Base class, int x = 2

运行成功(总计时间: 312毫秒)

 

注意,都是调用的父类中的函数.

 

 

package cn.vicky; public class MyTest { public void add(int i) { System.out.println("in parent"); } public static void main(String[] args) { MyTest2 m2 = new MyTest2(); m2.add(1); m2.add(1.1); } } class MyTest2 extends MyTest { public void add(double i) { System.out.println("in child"); } }   

 

in parent
in child

Java却可以区分...

你可能感兴趣的:(C/C++与Java函数重载区别!)