关于子类中virtual可有可无的讨论

有这样一个问题:

是不是一个父类写了一个virtual 函数,如果子类覆盖它的函数不加virtual ,也能实现多态? 

一般的回答是也可以实现多态。究其原因,有人说virtual修饰符是会隐式继承的。这样来说,此时virtual修饰符就是可有可无的。

又有人说,当用父类去new这个子类时,不加virtual的函数会 有问题的,应该加上。

我写了个例子,想去验证一下不加virtual时会不会有问题:

// TestPolymorphic.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Animal
{
public:
	Animal(){cout<<"animal constructor"<<endl;}
	virtual ~Animal(){cout<<"animal destructor"<<endl;}
	virtual void cry() const{cout<<"animal cry..."<<endl;}

};

class Dog:public Animal
{
public:
	Dog(){cout<<"dog constructor"<<endl;}
	virtual ~Dog(){cout<<"dog destructor"<<endl;}
	void cry() const{cout<<"dog cry..."<<endl;}
};

class Wolfhound:public Dog
{
public:
	Wolfhound(){cout<<"Wolfhound constructor"<<endl;}
	virtual ~Wolfhound(){cout<<"Wolfhound destructor"<<endl;}
	void cry() const{cout<<"Wolfhound cry..."<<endl;}
};

int _tmain(int argc, _TCHAR* argv[])
{
	Animal *pAnimal = new Wolfhound();
	static_cast<Wolfhound*>(pAnimal)->cry();
	delete pAnimal;
	getchar();
	return 0;
}
结果打印出来的与预期的一样:


这就说明了不加virtual是没有问题的。

昨天翻看了一下钱能老师的《C++程序设计教程》,

有过如下一段话:

一个类中将所有的成员函数都尽可能地设置为虚函数总是有益的。

下面是设置虚函数的注意事项:

1、只有类的成员函数才能声明为虚函数。

2、静态成员函数不能使虚函数,因为它不受限于某个对象。

3、内联函数不能使虚函数。

4、构造函数不能是虚函数。


正如weiqubo这位网友告知的:那些函数都应该加virture吧.

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值