c++ - 为什么我在继承程序中得到垃圾总和?
问题描述
为什么我使用多级继承在输出中得到垃圾总和?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;
}
解决方案
为什么我收到垃圾总和
因为您读入的值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 方法。
推荐阅读
- java - 计算二维数组中的相邻数字
- django - 在 django 中使用位置的最佳方式是什么
- three.js - 十二面体表面的星暴
- google-sheets - 将值包含逗号的列中的每一行拆分为转置行
- ios - onAppear SwiftUI iOS 14.4
- python - Python中向量化矩阵的对应坐标
- r - 为什么我无法在我的新 Windows 计算机上安装 R 包?
- javascript - 在我点击隐藏后,屏幕将向下,精确到页脚
- c# - 接受与剧作家夏普的对话
- node.js - 如何使用 PouchDB (leveldb) 将我的电子应用程序与 Cloudant 或任何其他支持 couchDB 和同步的数据库连接起来