繁体   English   中英

Function 过载和 inheritance 在 C++

[英]Function overloading and inheritance in C++

Suppose I have classes Bulldog and Labrador which publicly derive from base class Dog, and I have a function, eg a method of a different class, called reward, and I want it to produce different results for objects of class Dog and Bulldog, or for class 斗牛犬和拉布拉多犬的对象。 对于 C++ 开发人员来说,这样做的最佳方法是什么?

我知道如果 Dog 有任何虚函数,那么我可以为此目的使用dynamic_cast 那是你会推荐的吗? 如果不是,您认为最好的方法是什么?

直接的方法是使用多态性从reward(const Dog& dog) function(自由函数/其他类)委托给Dog接口的虚拟 function,使用提供的Dog引用,该引用可以多态地调度虚拟Dog方法。 例如:

#include <iostream>

struct Dog {
    Dog() {}
    virtual ~Dog() {}
    virtual void reward() const { 
        std::cout << "Default dog reward.\n"; 
    }
};

struct Bulldog : public Dog {
    Bulldog() {}
    ~Bulldog() override {}
    void reward() const override {
        std::cout << "Bulldog reward.\n"; 
    }
};

void reward(const Dog& dog) {
    dog.reward();    
}

int main() {
    reward(Dog{});     // Default dog reward.
    reward(Bulldog{}); // Bulldog reward.
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM