【问题标题】:Calling member of added classes with multiple inheritance调用具有多重继承的添加类的成员
【发布时间】:2014-01-08 09:24:59
【问题描述】:

我有 4 节课:

  • 列表
  • 基础
  • 一个
  • B

我需要添加一个类来扩展 A 和 B - L3 类的工作。 NewA 和 NewB 类实现了 L3 中声明的函数。

class Base
{
     virtual void foo() = 0;
}

class A: virtual public Base
{
     void foo();
}
class B: virtual public Base
{
     void foo();
}

class L3: virtual public Base
{
     virtual void bar() = 0;
}
class NewA: public A, virtual public L3
{
     void bar();
}

class NewB: public B, virtual public L3
{
     void bar();
}

如何在 List 中调用函数 bar()?

UPD

第一个列表包含对象 A 和 B,但现在有 NewA 和 NewB

class List
{
    public:
        void append(Base *sh);
        void next();
        void setBegin();
        Base* curr();
        void out(std::ofstream &ofst);

    protected:
        std::list <Base*> container;
        std::list <Base*>::iterator iter;
}

void List:: next()
{
    iter++;
}

void List:: setBegin()
{
    iter = container.begin();
}

void List:: append(Base* sh)
{
    container.push_back(sh);
}

Base* List::curr()
{
    return *iter;
}

void List::out(ofstream &ofst)
{
    setBegin();
    for (int i=0; i<container.size(); i++)
    {
        cout<<"Out: "<< endl; // I need to call bar() at this line
        next();
    }
}

【问题讨论】:

  • 你没有显示课程List。这让你的问题有点难以回答。

标签: c++ virtual multiple-inheritance


【解决方案1】:

Base 没有方法bar(),只有L3(及其派生类)有。 所以你不能从Base调用bar()

您可以执行以下操作:

Base* base = List.curr();
L3* l3 = dynamic_cast<L3*>(base); // l3 is non null if base is non null and IS a L3.

if (l3 != nullptr) {
    // base->bar(); // ILLEGAL
    l3->bar();
}

如果您知道Base L3,您可以使用static_cast

NewA newA;
Base* base = &newA;
L3* l3 = static_cast<L3*>(base);

newA.bar();
// base->bar(); // ILLEGAL
l3->bar();

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 2011-02-07
    • 1970-01-01
    • 2019-03-23
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多