【发布时间】:2014-09-13 16:32:09
【问题描述】:
如果我有一个基类和一个派生类:
class Base {
//...
};
class Derived : public Base {
//...
};
是否可以通过以下方式重载函数?
void DoSomething(Base b) {
cout << "Do Something to Base" << endl;
}
void DoSomething(Derived d) {
cout << "Do Something to Derived" << endl;
}
如果我这样做会发生什么:
int main() {
Derived d = Derived();
DoSomething(d);
}
Derived 也是 Base.. 那么调用哪个版本?
【问题讨论】:
-
将调用函数的最佳匹配,在你的情况下它应该是
void DoSomething(Derived d)。但你也应该问自己:你能用另一种方式做吗?例如类层次结构中的虚函数? -
@user2436815 'fu' 你的意思是你受苦了吗?来吧:That's so easy to check :P ...
-
@user2436815 Ouch! 难怪这条评论被删除了(无论如何都可能被解释为粗鲁)。无论如何,你应该澄清你实际上在问什么。正如我的链接所示,您发布的问题确实很容易解决。
标签: c++ inheritance polymorphism overloading