【问题标题】:C++ cast to base class [duplicate]C ++强制转换为基类[重复]
【发布时间】:2017-08-12 05:38:21
【问题描述】:

我有一个基类A 和一个派生类B

class A {
public:
    int x;
    virtual int getX() {
        return x;
    }
};

class B : public A {
public:
    int y;
};

虚函数只是为了使其具有多态性。 接下来我声明A 的列表,但将B 放在里面:

vector<A> list;
B b1,b2;
b1.y = 2;
b2.x = 10;

list.push_back(b1);
list.push_back(b2);

现在我想检查向量上的所有元素并访问y 成员(只有B 有):

for (auto it = list.begin(); it != list.end(); ++it) {
    B &cast = dynamic_cast<B&>(*it);
    int value = cast.y;
    std::cout << value << std::endl;
}

此代码给出运行时错误。知道如何进行演员表并访问y吗?

【问题讨论】:

标签: c++ casting polymorphism


【解决方案1】:

正在发生的事情是object slice

实现您正在寻找的一种方法是:

#include <vector>
#include <iostream>

using namespace std;

class A {
  public:
    int x;
    virtual int getX() {
      return x;
    }

    virtual ~A() = default;
};

class B : public A {
  public:
    int y;
};

int main() {
  vector<A*> list;
  B b1,b2;
  b1.y = 2;
  b2.x = 10;

  list.push_back(&b1);
  list.push_back(&b2);

  for (auto it = list.begin(); it != list.end(); ++it) {
    B* cast = dynamic_cast<B*>(*it);
    int value = cast->y;
    std::cout << value << std::endl;
  }

  return 0;
}

在这个示例代码中,我们使用指针来避免对象切片。
正如cdhowie 所说:运行时多态需要使用指针或引用

另一件重要的事情:在创建类层次结构时,请始终使您的基类析构函数为虚拟,否则您将遇到内存问题

【讨论】:

  • 相关点:运行时多态性要求使用指针或引用。值在运行时永远不能是多态的。
猜你喜欢
  • 2017-01-20
  • 2017-10-05
  • 2011-07-15
  • 1970-01-01
相关资源
最近更新 更多