【问题标题】:converting base class pointer to unknown derived class pointer将基类指针转换为未知的派生类指针
【发布时间】:2017-05-24 14:40:50
【问题描述】:

我有 5 个来自抽象基类的派生类。 一个函数被重载,它存在于每个派生类中,我们将其命名为print()。 Derived 4 类的示例:

Derived4::print(*Derived1)
Derived4::print(*Derived2)
Derived4::print(*Derived3)
Derived4::print(*Base)

就像我之前说的,所有派生类都有打印功能,但是参数不同,比如

Derived1::print(*Derived2)
Derived1::print(*Derived3)
Derived1::print(*Derived4)
Derived1::print(*Base)

所有对象都存储在一个向量中

vector<Base*> a

当我从向量中取出其中一个并尝试调用 print 函数时,所有调用都被定向到 print(*Base) 函数。我不允许存储类型,因此不知道来自什么向量。另外,也不允许类型检查。

一个例子:

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    void print(){cout << "greetings from A" << endl;}
};

class C : public A{
public:
    void print(){cout << "greetings from C" << endl;}
};

class D : public A{
public:
    void print(){cout << "greetings from D" << endl;}
}; 

class B : public A{
public:
    void print(C* c){c->print();}
    void print(A* d){d->print();}
};

int main()
{
    D d;
    C c;
    B b;
    vector<A*> a; //B,C,D will be stored inside a vector like this.
    a.push_back(&c);
    a.push_back(&d);
    b.print(a[0]);
    b.print(a[1]);
    return 0;
}

结果:

greetings from A
greetings from A

想要的结果:

greetings from C
greetings from A

【问题讨论】:

  • 在您的解释中,每个类都有不同的print 函数(不同的参数),而在您的示例中,所有类(B 除外)都具有相同的函数(相同的参数)- 是哪一个?
  • 但是一般来说,对于向下转换,您应该使用 dynamic_cast 并检查转换是否成功(返回非空值)
  • 不要介意示例代码,我只填写了B类。我只想展示一个关于结果的示例。
  • 你为什么不做多态呢?

标签: c++ inheritance abstract


【解决方案1】:

你需要虚函数。将A::print 声明为虚拟会使得在A 类型的指针上调用print 将调用对象构造为哪个类的print,而不是使用指针类型来决定要调用的print

如果对象的类型为D,您还需要删除D::print,如您所期望的那样调用A::print

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    virtual void print(){ cout << "This is printed twice." << endl; }
};

class C : public A{
public:
    void print(){ cout << "This is desired output." << endl; }
};

class D : public A{

};

class B : public A{
public:
    void print(C* c){ c->print(); }
    void print(A* d){ d->print(); }
};

int main()
{
    D d;
    C c;
    B b;
    vector<A*> a; //B,C,D will be stored inside a vector like this.
    a.push_back(&c);
    a.push_back(&d);
    b.print(a[0]);
    b.print(a[1]);
    return 0;
}

结果:

This is desired output.
This is printed twice.

【讨论】:

    猜你喜欢
    • 2013-09-23
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2014-03-09
    相关资源
    最近更新 更多