当前位置:编程学习 > C/C++ >>

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

有这样一个问题:
是不是一个父类写了一个virtual 函数,如果子类覆盖它的函数不加virtual ,也能实现多态?
一般的回答是也可以实现多态。究其原因,有人说virtual修饰符是会隐式继承的。这样来说,此时virtual修饰符就是可有可无的。
又有人说,当用父类去new这个子类时,不加virtual的函数会 有问题的,应该加上。
我写了个例子,想去验证一下不加virtual时会不会有问题:
[cpp] 
// 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++程序设计教程》,
有过如下一段话:www.zzzyk.com
一个类中将所有的成员函数都尽可能地设置为虚函数总是有益的。
下面是设置虚函数的注意事项:
1、只有类的成员函数才能声明为虚函数。
2、静态成员函数不能使虚函数,因为它不受限于某个对象。
3、内联函数不能使虚函数。
4、构造函数不能是虚函数。

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

作者:lincyang
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,