c++ virtual初步解析
c++ virtual初步解析
总结: virtual主要用于实现多态,使用场合是: 通过基类指针操作子类,在运行期动态选择子类方法而实现了多态。
虚函数和纯虚函数
虚函数可以被子类重写, 纯虚函数必须被子类重写。 虚函数是实现多态所必需的。发生继承操作时,同时继承基类所有的可继承项(public or proteced修饰)。
倘若基类方法未用virtual修饰,使用基类指针调用子类方法时,输出的将是基类的方法!因为在编译期时把基类指针指向子类,运行期仍是执行基类,所以调用的是基类方法;若采用virtual修饰,则是在运行期时动态选择子类方法,从而实现了多态。
#include <iostream>
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
虚继承
为了解决“钻石问题”而提出的方法。
继承关系如下:
这样,若B,C不虚继承自A, 那么D中将有两份A类的成员Foo。 在D的实例调用Foo方法时,就不知道是从B.Foo 还是 C.Foo了。
若采用了虚继承,那么D中仅有一份Foo,就很明确了。
虚析构函数
当基类指针指向子类实例,进行删除时,必须将基类的析构函数定义为virtual.
class Base {
// some virtual methods};
class Derived : public Base{
~Derived()
{
// Do some important cleanup
}};
// some virtual methods};
class Derived : public Base{
~Derived()
{
// Do some important cleanup
}};
Base *b = new Derived();
// use b
delete b; // Here's the problem!
// use b
delete b; // Here's the problem!
路漫漫其修远兮,吾将上下而求索