尽管在派生类中定义了方法,但在基类中不可见;多态性并使用`virtual`关键字

问题描述 投票:0回答:1
class A {
    protected:
        int foo;
};

class B : public A {
    public:
        B(int bar) { foo = bar; }
        int method() { return foo; }
};

class C {
    private:
        A baz;
    public:
        C(A faz) { baz = faz; }
        A get() { return baz; }
};

int main(void) {
    C boo(B(1));
    boo.get().method();
    return 0;
}

我有一个基类A,其中B是其派生类。类C需要一个A,但我已经通过了派生类(B)来代替。没有警告或错误,无法将B传递给C,但在上述情况下,我希望方法可见性为method()

我对virtual不太熟悉,但是我确实尝试将virtual int method() = 0;添加到A,这会导致进一步的错误。

考虑添加第二个派生类:

class D : public A {
    public:
        D(int bar) { foo = bar; }
        int method() { return foo+1; }
};

我希望C可以采用BD,而我最好的假设是采用A并对其进行处理。

如何以这种方式正确使用多态?

c++ inheritance polymorphism virtual c++03
1个回答
0
投票
#include <iostream>

class A {
    public:
        virtual ~A(){}
        virtual int method() = 0;
    protected:
        int foo;
};

class B : public A {
    public:
        B(int bar) { foo = bar; }
        int method() { 
            std::cout << "Calling method() from B" << std::endl;
            return foo; }
};

class C {
    private:
        A* baz;
    public:
        C(A* faz) { baz = faz; }
        A* get() { return baz; }
};

int main(void) {
    A* element = new B(1);
    C boo(element);
    boo.get()->method();
    return 0;
}

它打印“从B调用方法()”。但这是出于演示目的。请考虑使用智能指针。

© www.soinside.com 2019 - 2024. All rights reserved.