【问题标题】:C++ Method overloading by Inherited Parameter Type通过继承的参数类型重载 C++ 方法
【发布时间】: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


【解决方案1】:

是的,C++ 允许您为基类和派生类重载函数。事实上,标准库&lt;algorithm&gt;函数使用这种机制来根据传入的迭代器类型选择正确的算法。

Derived 对象也是 Base,但 DoSomething(Derived) 是完全匹配的,因此是首选。 DoSomething(d) 将调用DoSomething(Derived)

但是,请注意,您无法通过这种方式获得多态行为。也就是说,如果您有一个实际引用Derived 对象的Base&amp;,它仍然调用DoSomething(Base):也就是说,它在静态类型上调度。 (实际上,由于您是按值传递,它只将对象的 Base 部分复制到参数中。)要获得多态行为,您必须将 DoSomething 设为虚拟成员函数(或将 @ 987654332@在b上调用一个虚成员函数。)

【讨论】:

    【解决方案2】:

    派生函数将被调用和使用,因为它匹配这个“DoSomething(Derived d)” 签名。

    您是否考虑过使用这样的代码:

    #include<iostream>
    using namespace std;
    class Base {
    public:
        virtual void DoSomething();
    };
    
    class Derived : public Base {
    public:
        void DoSomething() override;
    };
    void Base:: DoSomething() {
        cout << "Do Something to Base" << endl;
    }
    
    void Derived :: DoSomething() {
        cout << "Do Something to Derived" << endl;
    }
    int main() {
        Base *d = new Derived();
        d->DoSomething();
        delete d;
        return 0;
    }
    

    它完成了相同的任务,并允许您利用多态性的优势。

    【讨论】:

    • '... of polymorphisms strength' 是的,所有的分层类设计都在后面:P ...
    • 与任何工具一样,它也有自己的优点和缺点。但是,是的,分层类设计可以尝试。
    猜你喜欢
    • 1970-01-01
    • 2014-12-25
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2016-02-19
    • 1970-01-01
    • 2023-02-09
    相关资源
    最近更新 更多