java和c++两门语言对于父子类中同名函数具有不同的处理方式。
先上两段代码:
C++: class Basic { public: void test(string i){ cout << "basic str" <<endl; } void test(int i){ cout << "basic" <<endl; } }; class Senior : public Basic { public: void test(long i){ cout << "senior 1" <<endl; } }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; Senior ps; ps.test(23); string str("c"); ps.test(str); return 0; } //输出结果编译错误,提示No viable conversion from ‘string‘ (aka ‘basic_string<char, char_traits<char>, allocator<char> >‘) to ‘long‘ 修改标红的代码--> ps.Basic::test(str) 则可以编译成功,并输出预期的结果 senior 1 basic str
public class Basic{ public int testException(int val) { try{ int j = 3/1; return j; } catch(Exception e){ return -1; } } public String testException(String val) { try{ return new String("ac"); } catch(Exception e){ return new String("bc"); } } }; public class Senior extends Basic{ public Long testException(Long val) { try{ return (long) 9; } catch(Exception e){ return (long) 7; } } } public static void main(String args[]) throws InstantiationException, IllegalAccessException, SecurityException, Exception{ // 向控制台输出信息 Senior ba = new Senior(); System.out.println("basic:" + ba.testException(2)); System.out.println("basic:" + ba.testException("123")); } } 输出结果 basic:3 basic:ac
比较这个例子中的不同,原因是java语言中父类和子类的同名函数做的是重载处理,而C++中是隐藏父类中的函数,如果需要调用父类中同名函数,需要显式指定调用(通过class::funtion_name)。
时间: 2024-10-26 00:09:16