c++ - 为什么我在继承程序中得到垃圾总和?

标签 c++ inheritance

为什么我在使用多级继承的输出中得到垃圾总和? 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;
}

最佳答案

why i am getting garbage sum


因为您在b1.input()中读取的值存储在与在c1.sum()中打印的值不同的对象中。
您要添加未初始化的int,因此程序的行为是不确定的。
也许你想要
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;
}
因为CB,所以您可以使用B的方法来调用。

关于c++ - 为什么我在继承程序中得到垃圾总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63132649/

相关文章:

c++ - 多重继承 C++,转换是如何工作的?

c++ - 错误 C2593 : 'operator +' is ambiguous

c++ - SDL_GetRelativeMouseState 奇怪的行为

c++ - "does not name a type"简单程序错误

c++ - 我可以在 C++ 中使用哪一行代码来禁用节能器?

c++ - 如何将shared_ptr转换为私有(private)基类?

javascript - JavaScript 中的继承

ruby - Ruby 中 Class 和 BasicObject 哪个先出现?

c++ - 使用 gcc 4.8.4/clang3.4 编译 Nana 示例 (nana v1.1.2/1.1.3) 时出错

java - JPanel 的扩展类不显示 JPanel 的属性