C++中的虚函数
终于放假了,可以想干嘛干嘛了,今天早上想到以前看过几篇大神的博客,里面提到说用父类的指针去访问子类的函数。。今天早上没什么事,就来验证一下。
[cpp]
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"initial Base Class"<<endl;
}
void name()
{
cout<<"Base Class name"<<endl;
}
};
class Derived1:public Base
{
public:
Derived1()
{
cout<<"initial Derived Class"<<endl;
}
void name()
{
cout<<"Derived1 Class name"<<endl;
}
};
int main()
{
Derived1 Derived1Class;
Derived1Class.name();
//这个当然是可以正常运行的
Base* BaseClassPointer;
BaseClassPointer=(Base*)&Derived1Class;
BaseClassPointer->name();
//这样相当于把子类转换为父类类型,然后去调用父类的name函数
return 0;
}
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"initial Base Class"<<endl;
}
void name()
{
cout<<"Base Class name"<<endl;
}
};
class Derived1:public Base
{
public:
Derived1()
{
cout<<"initial Derived Class"<<endl;
}
void name()
{
cout<<"Derived1 Class name"<<endl;
}
};
int main()
{
Derived1 Derived1Class;
Derived1Class.name();
//这个当然是可以正常运行的
Base* BaseClassPointer;
BaseClassPointer=(Base*)&Derived1Class;
BaseClassPointer->name();
//这样相当于把子类转换为父类类型,然后去调用父类的name函数
return 0;
}
运行结果
[cpp]
initial Base Class
initial Derived Class //初始化Deerived类
Derived1 Class name //调用Derived类的name()
Base Class name //发生强制转换,最终调用的是基类的name()
initial Base Class
initial Derived Class //初始化Deerived类
Derived1 Class name //调用Derived类的name()
Base Class name //发生强制转换,最终调用的是基类的name()
在不使用虚函数的情况下,用基类的指针去访问子类的函数。这样做就相当于把Derived1类型的对象强制转换为Base类型的,所以函数最终调用的是基类中的name()函数。
使用虚函数就可以实现用基类的指针去访问子类的函数,代码如下:
[cpp]
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"initial Base Class"<<endl;
}
virtual void name() //用虚函数来实现
{
cout<<"Base Class name"<<endl;
}
virtual ~Base()
{
}
};
class Derived1:public Base
{
public:
Derived1()
{
cout<<"initial Derived Class"<<endl;
}
void name()
{
cout<<"Derived1 Class name"<<endl;
}
~Derived1()
{
}
};
int main()
{
Derived1 Derived1Class;
Derived1Class.name();
//这个当然是可以正常运行的
Base* BaseClassPointer = (Base*)&Derived1Class;
BaseClassPointer->name();
return 0;
}
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"initial Base Class"<<endl;
}
virtual void name() //用虚函数来实现
{
cout<<"Base Class name"<<endl;
}
virtual ~Base()
{
}
};
class Derived1:public Base
{
public:
 
补充:软件开发 , C++ ,