c++ - 继承示例未打印预期结果

标签 c++ inheritance

尝试记住基本的 C++ 内容(已经很久了),并尝试使用编译器。我创建了一个简单的基/子继承示例。

我希望下面的输出

index 0 is 0
index 1 is 1
index 2 is 2

而是得到:

index 0 is 0
index 1 is 2
index 2 is 0

谁能指出我犯的明显错误?

#include <cstdlib>
#include <iostream>

#include <stdio.h>
#include <string>
using namespace std;

class Base
{
public: 
    Base(){x=0;}
    int x;
};
class Derived : public Base
{
public:
    Derived() { y=0;}
    int y;
};

// practicing operator definition syntax
ostream& operator<<(ostream& ostr, const Base& base)
{
       ostr << base.x << endl;
       ostr << flush;
    return ostr;
}

void init(Base *b)
{
    for (int i = 0; i<3; i++)
    {
        b[i].x=i; 
    }
};

int main(int argc, char** argv)
{
    Derived arr[3];
    init(arr);
    for (int idx = 0; idx< 3; idx++)
    {
        cout << "index is " << idx << ' ' << arr[idx] << endl;
    }

    return 0;
}

最佳答案

数组和多态性在 C++ 中不能混用。

DerivedBase对象具有不同的大小,您程序中涉及的任何指针算法都会失败。

你的 init方法是切片 Derived Base 中的对象对象。以下赋值具有未定义的行为,它在 Derived 上的某处设置了一些字节对象。

考虑使用 std::vector<std::unique_ptr<B>>作为替代品。

此外,您的 Base类缺少其虚拟析构函数,稍后会调用更多未定义的行为。

关于c++ - 继承示例未打印预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24224577/

相关文章:

c++ - 命名空间 boost::detail 中没有名为 'dynamic_cast_tag' 的成员 (SALOME 7.3.0)

c++ - 如何存储或转发 CRTP 模板类的类型

c++ - C++ 中的整数到模板类型集合

c++ - 将派生类的 unique_ptr 添加到基类 unique_ptr 的 vector 中

c# - 如何避免类继承绕过?

c# - 继承抽象类的不同具体实现

c++ - 用 C++ 安装并运行 Windows 服务

c++ - 从派生**转换为基础**

c++ - 虚拟继承中断初始化列表显式构造函数调用

class - 如何在 UML 图中描述 Either/Or 继承?