一、修饰成员函数
#include <iostream>
using namespace std;
class A
{
public:A(){}
public:
virtual void func1(){ cout << "A vitual"; }
virtual void func2()
{
func1();
}
};
class B :public A
{
public:B(){}
public:
void func1(){ cout << "B vitual"; }
void func2(){
func1();
}
};
int main()
{
A *a = new B();
a->func2();
while (1);
return 0;
}
输出结果:
二、修饰类
#include <iostream>
using namespace std;
class A{
public:
A()
{
cout << "A构造" << endl;
}
~A()
{
cout << "A析构" << endl;
}
};
class B : virtual public A
{
public:
B()
{
cout << "B构造" << endl;
}
~B()
{
cout << "B析构" << endl;
}
};
class C : virtual public A
{
public:
C()
{
cout << "C构造" << endl;
}
~C()
{
cout << "C析构" << endl;
}
};
class D : public B, public C{
public:
D()
{
cout << "D构造" << endl;
}
~D()
{
cout << "D析构" << endl;
}
};
int main()
{
D *d = new D();
delete d;
while (1);
return 0;
}
执行结果:
类没有被vitual修饰时:
#include <iostream>
using namespace std;
class A{
public:
A()
{
cout << "A构造" << endl;
}
~A()
{
cout << "A析构" << endl;
}
};
class B : public A
{
public:
B()
{
cout << "B构造" << endl;
}
~B()
{
cout << "B析构" << endl;
}
};
class C : public A
{
public:
C()
{
cout << "C构造" << endl;
}
~C()
{
cout << "C析构" << endl;
}
};
class D : public B, public C{
public:
D()
{
cout << "D构造" << endl;
}
~D()
{
cout << "D析构" << endl;
}
};
int main()
{
D *d = new D();
delete d;
while (1);
return 0;
}
执行结果:
三、vitual修饰析构函数
#include <iostream>
using namespace std;
class A{
public:
A()
{
cout << "construct A" << endl;
}
virtual ~A()
{
cout << "destory A" << endl;
}
};
class B : public A{
public:
B()
{
cout << "construct B" << endl;
}
virtual ~B()
{
cout << "destory B" << endl;
}
};
int main()
{
A *a = new B();
delete a;
while (10);
return 0;
}
执行结果: