c为C ++盐我对虚函数有疑问。 [英] <C++> I have question about virtual functions.

查看:96
本文介绍了c为C ++盐我对虚函数有疑问。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <cstring>
#include <cstdlib>

using namespace std;

class Fir
{
public:
	virtual void mfunc() { cout << "First func" << endl; }
};

class Sec : public Fir
{
public:
	virtual void mfunc() { cout << "Second func" << endl; }
};

class Thi : public Sec
{
public:
	virtual void mfunc() { cout << "Third func" << endl; }
};

int main()
{
	Thi * tptr = new Thi();
	Sec * sptr = tptr;
	Fir * fptr = sptr;

	fptr->mfunc();
	sptr->mfunc();
	tptr->mfunc();
	delete tptr;
	return 0;
}





我的尝试:



当我执行上面的代码时,Third func会显示三次。我想知道为什么fptr-> mfunc()的结果是第三个函数而不是第二个函数,即使它指向一个Sec对象。



What I have tried:

When I execute the above code, "Third func" is displayed three times. I am wondering why the result of " fptr->mfunc()" is " Third func" instead of "Second func", even though it points to a Sec object.

推荐答案

虚拟方法按原样使用;或者你覆盖他们;你没有做过;你只是在每个班级中创建了一个替换虚拟方法。



在这种情况下尝试向下投射毫无意义。
Virtual methods are used "as is"; or you "override" them; you have done neither; you have simply created a "replacement" virtual method in each class.

Trying to "down cast" in this situation makes no sense.

这就是虚函数的目的:允许多态。

考虑一下,例如下面的代码

That's the very purpose of the virtual functions: to allow polymorphism.
Consider, for instance the following code
void draw_shapes( Shape * sh[], size_t count)
{
  for ( size_t n = 0; n < count; ++n)
    sh[n]->draw_myself();
}



数组中的每个项目(每个 Shape )将根据其真实性质绘制自己:例如, Circle Rectangle 将生成完全不同的图纸。



[更新]


every item of the array (every Shape) will draw itself depending on its real nature: a Circle and a Rectangle, for instance, will produce quite different drawings.

[Update]

引用:

有仍然有点令人困惑的部分。当前类的继承关系是Fir< -Sec< -Thi。如果调用虚函数,是否最后覆盖了thi类的mFunc()函数,以便三次输出相同的结果?

There is still a little confusing part. The inheritance relationship of the current classes is "Fir <- Sec <- Thi". If the virtual function is called, is the thi class's mFunc () function last overridden so that the same result is output all three times?





每个对象即使指针声明指定了基类,它也会执行自己的 mfunc 代码。尝试:



Every object performs its own mfunc code, even if the pointer declaration specifies the base class. Try:

int main()
{
  Fir * p[] = { new Fir(), new Sec(), new Thi()};

  for ( size_t n = 0; n < 3; ++n)
    p[n]->mfunc();

  for ( size_t n = 0; n < 3; ++n)
    delete p[n];
  
  return 0;
}

[/ Update]


这篇关于c为C ++盐我对虚函数有疑问。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆