C++ 继承 - 为什么调用父方法?

标签 c++ c++11 inheritance

这个问题在这里已经有了答案:





What is object slicing?

(18 个回答)


2年前关闭。




我正在实现一个类层次结构,并看到对我不明白为什么的父方法的调用。使用 C++11 结构,这是我第一个使用一些特性的 11 个项目,因此我相信这可能是一个良性问题。

class A{
   void update(){
       std::err << "Calling A update " << std::endl;
   } 
}

class B: public A{
   void update(){
       std::cout << "In B update! " << std::endl;
   } 
}

class C: public A{
   void update(){
       std::cout << "In C update! " << std::endl;
   } 
}

现在在其他地方我有一个包含 Bs 或 Cs 的 vector
std::vector<A> container;
container.push_back(B());
container.push_back(C());

for(auto item: container){
    item.update();
}

打印
Calling A update
Calling A update

为什么?

最佳答案

why is parent method called?



因为 vector 包含父对象。

It contains Bs and Cs, child objects.



它不包含那些对象。它是 A 的 vector 对象,因此它只包含 A 类型的对象,并且没有任何其他类型的对象。您从派生对象中复制了基类子对象(此操作称为切片)。拷贝不是基类子对象,而是单独的 A对象。

此外,您的派生类不会覆盖父类函数。只有虚函数可以被覆盖。只能通过指针或对基类子对象的引用间接调用虚函数来使用虚拟调度。

附言您也不能从类外部调用私有(private)成员函数。示例程序格式不正确。

关于C++ 继承 - 为什么调用父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59884625/

相关文章:

c++ - OpenGL 第一个立方体渲染不工作

c++ - c++什么时候程序不调用析构函数?

c++ - 您如何将所有链接依赖项打包到一个 Linux 静态库中?

c++ - c++11 lambdas 捕获他们不使用的变量吗?

inheritance - Scala从Java类继承: select which super constructor to call

java - 将instanceof 与其他继承数据一起使用时的混淆

c++ - OpenMP - 并行 For 循环

c++ - 在Windows 8.1中使用OpenCV在C++中加载图像需要很长时间

c++ - 如何解决 MSVC 2012 中的 `using K = ...`?

c++ - 虚函数和双重继承