父类的向下引用,用于类成员函数中的子类的引用

时间:2013-10-27 06:05:49

标签: c++ casting reference

我有一个类层次结构如下:

class Base
{
    public:
    virtual Base& derived() const=0;
}

class Derived:public Base
{
    public:
    Derived& derived() const
    {
        return dynamic_cast<Derived&>(*this);
    }
    void test(){cout<<"Hi";}
}

derived()的目的是返回确切类型的引用。

int main()
{
    Derived d;
    Base &b = d;
    (b.derived()).test();
    return 0;
}

我收到编译错误

can't find void test() in Base

在我查看时,Derived::derived()确实被调用了。似乎Derived::derived()未按预期返回对派生类的引用。

2 个答案:

答案 0 :(得分:0)

您是否忘记了样本中的遗传?像这样的东西会起作用,但设计很差。

class Base
{
public:
    virtual ~Base() { }
    template < typename T>
    const T& derived() const {
        return dynamic_cast<const T&>(*this);
    }
};

class Derived : public Base
{
public:
    void test() const {std::cout<<"Hi";}
};

int main(int argc, const char * argv[])
{
    Derived d;
    const Base& b = d;
    b.derived<Derived>().test();
}

答案 1 :(得分:0)

标准覆盖情况。我也包含了一个函数,因为你说你想把这个值作为参数传递。

class Base
{
public:
    virtual void test() const { }
};

class Derived : public Base
{
public:
    void test() const {std::cout<<"Hi";}
};

void func(const Base& b) {
    b.test();
}

int main(int argc, const char * argv[])
{
    Derived d;
    const Base& b = d;
    b.test();
    func(b);
}