0

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

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()没有按预期返回对派生类的引用。

4

2 回答 2

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);
}
于 2013-10-27T06:45:18.440 回答
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();
}
于 2013-10-27T06:17:39.223 回答