Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
继承Parameter Type的C++方法重载_C++_Inheritance_Polymorphism_Overloading - Fatal编程技术网

继承Parameter Type的C++方法重载

继承Parameter Type的C++方法重载,c++,inheritance,polymorphism,overloading,C++,Inheritance,Polymorphism,Overloading,如果我有一个基类和一个派生类: class Base { //... }; class Derived : public Base { //... }; 是否可以按以下方式重载功能 void DoSomething(Base b) { cout << "Do Something to Base" << endl; } void DoSomething(Derived d) { cout << "Do Something to De

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

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;
}

派生也是一个基础。。那么,调用哪个版本?

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

派生对象也是一个基础,但DoSomethingDerived是一个完全匹配的对象,因此首选它。DoSomethingd将调用DoSomethingDerived


但是,请注意,您无法通过这种方式获得多态行为。也就是说,如果有一个Base&它实际上引用了一个派生对象,那么它仍然调用DoSomethingBase:也就是说,它对静态类型进行分派。事实上,由于您是按值传递的,因此它只将对象的基本部分复制到参数中。要获得多态行为,必须将DoSomething设置为虚拟成员函数,或使DoSomethingBase&b调用b上的虚拟成员函数。

将调用并使用派生函数,因为它与此DoSomethingDerived匹配 签名

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

#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;
}

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

函数的最佳匹配将被调用,在您的情况下,它应该是void DoSomethingDerived。但你也应该问自己:你能用另一种方式吗?例如,在类层次结构中使用虚函数?@user2436815“fu”您的意思是说您正在遭受它的折磨吗?C'mon::P…@πάνταῥεῖ '“福”的意思是飞独角兽。对不起confusion@user2436815难怪这条评论被删除了,否则会被解读为粗鲁无礼。无论如何,你应该澄清你实际上在问什么。正如我的链接所示,你们所发布的问题其实是可以解决的。。。“多态性的力量”是的,所有的层次化类设计,这是后来出现的:P…与任何工具一样,它有自己的优点和缺点。但是,是的,分层类设计可以尝试。
#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;
}