首页 > 解决方案 > 为什么我在继承程序中得到垃圾总和?

问题描述

为什么我使用多级继承在输出中得到垃圾总和?sum 函数在类中c,对象c1在 main 函数中创建。

#include <iostream.h>
using namespace std;
class A {
public:
    int a, b;
};
class B : public A {
public:
    void input()
    {
        cout << "enter the values";
        cin >> a >> b;
    }
};
class C : public B {
public:
    void sum()
    {
        cout << a + b;
    }
};
int main()
{
    B b1;
    C c1;
    b1.input();
    c1.sum();
    return 0;
}

标签: c++inheritance

解决方案


为什么我收到垃圾总和

因为您读入的值b1.input()与您打印的值存储在不同的对象中c1.sum()

您正在添加未初始化int的 s,因此您的程序的行为是未定义的。

也许你想要

int main()
{
    C c1;
    B & b1 = c1;
    b1.input();
    c1.sum();
    return 0;
}

您在其中引用了对象的B基本子C对象。

或者更简单地说

int main()
{
    C c1;
    c1.input();
    c1.sum();
    return 0;
}

因为 aC a B,所以你可以用一个来调用B's 方法。


推荐阅读