mah*_*dix 1 c++ oop polymorphism overloading class
假设我们有这些重载的C++函数:
void paint(Shape s, Color c) {}
void paint(Circle ci, Color c) {}
void paint(Shape s, SolidColor sc) {}
Run Code Online (Sandbox Code Playgroud)
显然,Shape是父母Circle和Color父母的父母SolidColor.
如果我进行这样的函数调用:将调用paint(myCircle, mySolidColor)哪个版本的paint函数?
通常,当多个参数可以是层次结构中的任何类型时,如何解析多个分辨率候选的方法调用?
(我希望我的问题+示例足够清楚,但如果有歧义让我知道)
PS还有这个电话怎么样?
Color* c = create_color(); //returns SolidColor instance
Shape* s = create_shape(); //returns Circle instance
paint(s,c);
Run Code Online (Sandbox Code Playgroud)
将调用哪种版本的油漆?
给定您的代码,元素将在传递给函数时被复制,并且切片:例如,在第一次重载时,如果传递给它,Shape s将只是松散的Circle信息Circle.如果Shape是抽象的,则此代码甚至不会编译.
它的要点是这个代码不会像Java/C#中的类似代码那样实现多态行为.
第二点是重载解析发生在运行时多态之前:也就是说,编译器在编译时选择调用函数,通过选择最匹配的函数原型.
如果你有 :
int main() {
Circle myCircle;
SolidColor mySolidColor;
paint(myCircle, mySolidColor);
}
Run Code Online (Sandbox Code Playgroud)
然后编译器会因为模糊而抱怨,因为重载2和3都可以同样工作.
最重要的是,对于C++中的多态性,您希望通过引用传递参数:
void paint(Shape& s, Color& c) {}
void paint(Circle& ci, Color& c) {}
void paint(Shape& s, SolidColor& sc) {}
Run Code Online (Sandbox Code Playgroud)
如果有歧义让我知道
这里是一个含糊不清; 它正在通话中!
paint(Circle{}, SolidColor{});
Run Code Online (Sandbox Code Playgroud)
这个调用是不明确的,因为对于这个调用,没有过载比其他过载更专业.Clang给出了这个错误:
main.cpp:11:5: error: call to 'paint' is ambiguous
paint(Circle{}, SolidColor{});
Run Code Online (Sandbox Code Playgroud)
通常,当多个参数可以是层次结构中的任何类型时,如何解析多个分辨率候选的方法调用?
这称为重载解析,并且在特定的SO答案中涉及的主题太多了.关于该主题的cppreference文章应该为您提供合理的概述.