C++方法按继承参数类型重载

use*_*815 -1 c++ polymorphism inheritance overloading

如果我有一个Base和一个派生类:

class Base {
  //...
};

class Derived : public Base {
  //...
};
Run Code Online (Sandbox Code Playgroud)

是否可以通过以下方式重载功能?

void DoSomething(Base b) {
    cout << "Do Something to Base" << endl;
}

void DoSomething(Derived d) {
    cout << "Do Something to Derived" << endl;
}
Run Code Online (Sandbox Code Playgroud)


如果我这样做会发生什么:

int main() {
    Derived d = Derived();
    DoSomething(d);
}
Run Code Online (Sandbox Code Playgroud)

Derived也是一个Base ..所以调用哪个版本?

Bri*_*ian 11

是的,C++允许您重载基类和派生类的函数.实际上,标准库<algorithm>函数使用此机制来根据传入的迭代器的类型选择正确的算法.

Derived对象也是一个Base,但DoSomething(Derived)是精确匹配,所以它是优选的.DoSomething(d)会打电话DoSomething(Derived).

但请注意,您不能以这种方式获得多态行为.也就是说,如果你有一个Base&实际引用的Derived对象,它仍然会调用DoSomething(Base):也就是说,它会调度静态类型.(事实上​​,由于您通过值传递,它只Base将对象的一部分复制到参数中.)要获得多态行为,您必须DoSomething进入虚拟成员函数(或DoSomething(Base& b)调用虚拟成员函数)b. )