C ++转换为基类

And*_*tos 5 c++ polymorphism casting

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

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

class B : public A {
public:
    int y;
};
Run Code Online (Sandbox Code Playgroud)

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

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

list.push_back(b1);
list.push_back(b2);
Run Code Online (Sandbox Code Playgroud)

现在我想遍历向量上的所有元素并访问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;
}
Run Code Online (Sandbox Code Playgroud)

此代码给出了运行时错误。知道我该如何进行投射和访问y吗?

rcm*_*ite 2

正在发生的是一个对象切片。

实现您所寻求的目标的一种方法是:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

另一件重要的事情:创建类层次结构时,始终将基类析构函数设为虚拟,否则会出现内存问题

  • 相关点:运行时多态性*需要*使用指针或引用。值在运行时永远不可能是多态的。 (3认同)