本文介绍了奇怪的重载行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以下是三个简单的课程: A级 { public void DoIt(B b) { DoSomething(b); } public void DoSomething(B b) { } public void DoSomething(C c) { } } B级 { } C级: B { } 这是一些带行号的简单代码: 1. A a = new A(); 2. C c = new C(); 3. a.DoSomething(c); 4. a.DoIt(c); 这是我的问题: 第3行将导致重载方法A.DoSomething(C c)被调用,但 第4行导致A.DoSomething(B b)被调用。为什么?如果你问我,那看起来很糟糕 。是的,我可以看到第一种被调用的方法是DoIt(B b),这显然会导致错误。后续的方法被调用。 但这种行为的基本原理是什么?Here are three simple classes:class A{public void DoIt(B b){DoSomething(b);}public void DoSomething(B b){}public void DoSomething(C c){}}class B{}class C : B{}Here is some simple code with line numbers:1. A a = new A();2. C c = new C();3. a.DoSomething(c);4. a.DoIt(c);Here is my question:Line 3 will cause the overloaded method A.DoSomething(C c) to be called, butline 4 causes A.DoSomething(B b) to be called. Why? That seems pretty wackif you ask me. Yes, I can see that the first method to be called is DoIt(Bb), which then apparently causes the "wrong" subsequent method to be called.But what is the underlying rationale for such behavior?推荐答案 因为否则在编译时很难预测。 方法*签名*是在编译时选择的,调用的实际方法 取决于覆盖(不重载)。 这肯定是Java工作的方式,我怀疑它是如何使用C ++的工作(虽然我还没有检查过)。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复小组,请不要给我发邮件Because otherwise things would be hard to predict at compile time. Themethod *signature* is chosen at compile time, and the actual methodinvoked depends on overriding (not overloading).This is certainly the way Java works as well, and I suspect it''s howC++ works (although I haven''t checked).--Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me too 根据 $ b $的类型和/或数量调用重载方法b传递给他们的参数。 DoIt期望一个B类型的对象。一个C对象 是一个B对象,所以你可以将一个C传递给DoIt。但是,DoIt会将 对象强制转换为基类B的实例。当DoIt调用DoSomething时, 你会得到DoSomething(B b)而不是DoSomething(C c) 。 如果您直接调用DoSomething,则遵循相同的规则。 但是,因为您没有将C对象转换为其实例 base,调用正确的方法并执行DoSomething(C c)。 - 有10种人那些懂二元的人和那些没有b $ b的人。 http://code.acadx.com (拉针回复)Overloaded methods get called based upon the type and/or number ofarguments passed to them. DoIt expects an object of type B. A C objectis a B object so you can pass a C to DoIt. However, DoIt will cast thatobject to an instance of the base class B. When DoIt calls DoSomething,you get DoSomething(B b) not DoSomething(C c).Where you call DoSomething directly, the same rules are followed.However, since you''re not casting your C object to an instance of itsbase, the correct method is called and DoSomething(C c) gets executed.--There are 10 kinds of people. Those who understand binary and those whodon''t. http://code.acadx.com(Pull the pin to reply) 这篇关于奇怪的重载行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-15 11:42