为什么我在使用多级继承的输出中得到垃圾总和? 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;
}
因为C
是B
,所以您可以使用B
的方法来调用。
关于c++ - 为什么我在继承程序中得到垃圾总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63132649/