简体   繁体   English

c ++如何在抽象父类中调用子方法?

[英]c++ How to call child method in abstract parent class?

I have a problem with my code. 我的代码有问题。

class A{
    virtual foo()=0;
}

class B: public A {
    foo();
    foo2();
    operator X(A * a) {a->foo2()}   //doesn't work
}

class C: public A {
    foo();
    foo2();
    operator X(A * a) {a->foo2()} //doesn't work.
}

So I have a virtual class, and 2 classes that inherit from it. 因此,我有一个虚拟类,以及从其继承的2个类。 And I have to define an operator X that acts on an A object, no matter if it is B or C (since it can't be A because A is abstract). 而且我必须定义一个作用于A对象的运算符X,无论它是B还是C(因为它不可能是A,因为A是抽象的)。 The problem is that the operator calls foo2(), which I'm not allowed to write in class A. What should I do? 问题在于操作员调用了foo2(),我不允许它在类A中编写。该怎么办?

Thanks a lot for helping me. 非常感谢您的帮助。 This is my first post. 这是我的第一篇文章。

The right answer is to declare foo2 pure virtual in A. However you have been told you are not allowed to do this. 正确的答案是在A中声明foo2纯虚拟。但是,您被告知不允许这样做。 Boo :-( 嘘:-(

Your only remaining option is to use dynamic_cast . 您唯一剩下的选择是使用dynamic_cast

void do_foo2(A* a)
{
    if (B* b = dynamic_cast<B*>(b))
        return b->foo2();
    C& c = dynamic_cast<C&>(*a);  // Will throw if a is not B or C.
    return c.foo2();
}

Then 然后

void B::operator X(A* a)
{
    do_foo2(a);
}

Note: This all assumes you are supposed to make B::operator X work with both B and C. 注意:这全部假设您应该使B::operator X与B和C一起使用。

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

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