C++继承问题,快来救命

来源:百度知道 编辑:UC知道 时间:2024/09/22 12:48:59
#include <iostream.h>
class Base
{
public:
Base(int x,int y){a=x;b=y;}
void Show(){cout<<"Base:"<<a<<","<<b<<endl;}
private:
int a,b;
};
class Derived:public Base
{
public:
Derived(int x,int y,int z):Base(x,y),c(z){}
void Show(){cout<<"Derived:"<<c<<endl;}
private:
int c;
};

void main()
{
Base b(50,50),*pb;
Derived d(10,20,30);
pb=&b;
pb->Show();
pb=&d;
pb->Show();
}
为什么会是输出:Base:50,50
Base:10,20
哪位大哥可以帮忙解释一下.....先谢了

因为Show()不是虚函数,所以没有多态性啊之类的。所以pb是B指针类型,虽然指向派生类,但调用的函数仍然先从自己(基类)找起。

#include <iostream.h>
class Base
{
public:
Base(int x,int y){a=x;b=y;}
virtual void Show(){cout<<"Base:"<<a<<","<<b<<endl;}
private:
int a,b;
};
class Derived:public Base
{
public:
Derived(int x,int y,int z):Base(x,y),c(z){}
void Show(){cout<<"Derived:"<<c<<endl;}
private:
int c;
};

void main()
{
Base b(50,50), *pb;
Derived d(10,20,30);
pb=&b;
pb->Show();
pb=&d;
pb->Show();
}

#include <iostream.h>
class Base
{
public:
Base(int x,int y)//构造函数
{a=x;b=y;}
void Show()
{cout<<"Base:"<<a<<","<<b<<endl;}//输出a,b的值
private:
int a,b;//私有成员
};
/*
以公共的方式继承,注:一个类可以派生于多个类。