繁体   English   中英

在C ++中采用基类指针的函数,该基类指针已重载了指向子类的指针

[英]Function that takes a base class pointer in C++ that is overloaded with a pointer to a subclass

这是我的示例代码:

#include <iostream>
#include <vector>
#include <string>

class Animal {

};

class Rabbit : public Animal {

};

class Caller {
    public:
    virtual void call(Animal* a) {
        std::cout << "Caller calls animal" << std::endl;
    }

    virtual void call(Rabbit* r) {
        std::cout << "Caller calls rabbit" << std::endl;
    }
};


int main(int argc, char** argv) {
    std::vector<Animal*> v;
    Caller c;
    auto a = new Animal();
    auto r = new Rabbit();
    v.push_back(a);
    v.push_back(r);


    for(auto elem : v) {
        c.call(elem);
    }


    return 0;
}

此代码的输出可以在这里找到

http://ideone.com/I29g3A

它输出:

Caller calls animal
Caller calls animal

我想知道,没有将特定元素投射到Rabbit* ,有没有办法获取call(Rabbit *r)方法来进行调用?

当然,例如,通过在您的多态类系统中跳过合适的访问者。 我认为您需要使用两个名称来代替call() 我使用了pubCall()call()

#include <iostream>
#include <vector>
#include <string>

class Visitor;

class Animal {
public:
    virtual void visit(Visitor&);
};

class Rabbit : public Animal {
    void visit(Visitor&);
};

class Visitor
{
public:
    virtual void call(Animal* a) = 0;
    virtual void call(Rabbit* r) = 0;
};

void Animal::visit(Visitor& v) {
    v.call(this);
}

void Rabbit::visit(Visitor& v) {
    v.call(this);
}

class Caller
    : Visitor {
public:
    void pubCall(Animal* a) { a->visit(*this); }

private:
    virtual void call(Animal* a) {
        std::cout << "Caller calls animal" << std::endl;
    }

    virtual void call(Rabbit* r) {
        std::cout << "Caller calls rabbit" << std::endl;
    }
};


int main(int argc, char** argv) {
    std::vector<Animal*> v;
    Caller c;
    auto a = new Animal();
    auto r = new Rabbit();
    v.push_back(a);
    v.push_back(r);


    for(auto elem : v) {
        c.pubCall(elem);
    }


    return 0;
}

暂无
暂无

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

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