c++覆盖与隐藏,如果是覆盖,派生类还可以调用基类中被覆盖的原始函数吗,看清楚了——是基类中原始函数

来源:百度知道 编辑:UC知道 时间:2024/06/24 18:14:39
// bb.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream.h"

class person
{
public:
char *name;
int age;
person()
{
name="bhs";age=23;
}
person(char*str,int a)
{
name=str;age=a;
}
virtual show()
{
cout<<name<<endl<<age<<endl;
}
};
class student :public person
{
public:
int score;
int xh;
student()
{
score=90;
xh=2;
}
student(int a,int b,char *str,int c):person(str,c)
{
score=a;xh=b;
}
show()
{
cout<<name<<" "<<age<<" "<<score<<" "<<xh<<endl;
}
};
int main(int argc, char* argv[])
{
person bhs;
bhs.show();
student hyq(90

你要用基类的指针去访问覆盖了的函数这样才能看出效果。

你用了子类的指针去访问,带virtual的情况下,的确是覆盖,但是由于是子类的指针,所以你访问的肯定是子类的函数。不带virtual情况下,自然也访问的是子类的函数。

但是当你用父类的指针访问的时候,你用了virtual,在覆盖的时候会生成一个【虚函数表】,这个表记录了所有的虚函数,当你用父类的指针访问某个函数的时候,是用索引去这个表中去查,而不是根据函数名,所以,就用同名函数实现了类的多态。。。

明白了吗

如果不明白可以发信给我
给你资料

覆盖函数和被覆盖函数只有函数体不同,当派生类对象调用子类中该同名函数时会自动调用子类中的覆盖版本,而不是父类中的被覆盖函数版本,这种机制就叫做覆盖。

可以吧,不过我们一般都不这么用····
代码如下··

#include <iostream>

using namespace std;

class A
{
public:
virtual void print()
{
cout << "A" << endl;
}
};

class B : public A
{
public:
virtual void print()
{
cout << "B" << endl;
}
};

int main()
{
B *pb;
A a;

pb = (B *)&a;
pb->print();

return 0;
}

你那个肯定是没区别的啊··
hyq.person::show()
是看不出来的吧,要用基类的指针去访问派生类