c++没有给出预期的输出

C++ is not Giving Expected output

本文关键字:输出 c++      更新时间:2023-10-16

我是it专业的学生,在我们的课本中有很多简单继承的程序,但是这些都是很长的实用程序,所以很难理解和记住,所以我试图用c++编写一个简单的继承程序,但是程序没有给出预期的输出。

I've use c++ for windows 7

代码如下:

#include"iostream.h" 
#include"conio.h"
class A
{
public:
int a,b;
void setData(int i,int j)
{
   a=i;
   b=j;
}
};
class B: public A
{
   public:
   int compare()
   {
  return(a>b?a:b);
   }
};

void main()
{
A a;
B b;
//int c;
clrscr();
a.setData(25,9);

cout<<"answerswer: "<<b.compare();
getch();
}

输出如下

answer : 1213

所以请帮助我N告诉我为什么输出是这样!!!!我只是想学习

您在A类对象上使用setData,而在B类对象上调用compare。在这两种情况下都使用b

int main()
{
  A a;
  B b;
  //int c;
  clrscr();
  b.setData(25,9);

  cout<<"answerswer: "<<b.compare();
  getch();
  return 0;
}

也改变main方法的签名

ab是不同的对象,变量a,b存储在每个对象的内存空间中。您初始化了a的成员,并试图与对象b进行比较

So plz help me N tell me Why the Output is like this?

你得到的答案都是垃圾值