C++虚函数与Object Slicing

在写MFC应用程序的时候,有必要搞懂虚函数和Object Slicing. 

 我们首先来看一个极为简单的程序:

#include <iostream>
using namespace std;
 
class A
{
public:
	void f()
	{
		cout << "A::f" << endl;
		g();
	}
 
	void g()
	{
		cout << "A::g" << endl;
	}
 
};
 
class B : public A
{
public:
	void g()
	{
		cout << "B::g" << endl;
	}
};
 
int main()
{
	B b;
	b.f();           // A::f和A::g
	((A)b).f();      // A::f和A::g
 
	B *pb = new B;
	pb->f();         // A::f和A::g
	((A*)(&b))->f(); // A::f和A::g
 
	return 0;
}

现在把g函数设置为虚函数,得到程序为:

#include <iostream>
using namespace std;
 
class A
{
public:
	void f()
	{
		cout << "A::f" << endl;
		g();
	}
 
	virtual void g()
	{
		cout << "A::g" << endl;
	}
 
};
 
class B : public A
{
public:
	virtual void g()
	{
		cout << "B::g" << endl;
	}
};
 
int main()
{
	B b;
	b.f();           // A::f和B::g
	((A)b).f();      // A::f和A::g (Object Slicing)
 
	B *pb = new B;
	pb->f();         // A::f和B::g
	((A*)(&b))->f(); // A::f和B::g
 
	return 0;
}

原文链接:https://blog.csdn.net/stpeace/article/details/9004140

猜你喜欢

转载自blog.csdn.net/zpznba/article/details/88919271