虚函数和纯虚函数的区别

Difference between a virtual function and a pure virtual function(虚函数和纯虚函数的区别)
本文介绍了虚函数和纯虚函数的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

纯虚函数和虚函数有什么区别?

What is the difference between a pure virtual function and a virtual function?

我知道纯虚函数是一个没有实体的虚函数",但这意味着什么以及下面这行实际做了什么:

I know "Pure Virtual Function is a Virtual function with no body", but what does this mean and what is actually done by the line below:

virtual void virtualfunctioname() = 0

推荐答案

虚函数使其类成为多态基类.派生类可以覆盖虚函数.通过基类指针/引用调用的虚拟函数将在运行时解析.也就是说,使用对象的动态类型而不是它的静态类型:

A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:

 Derived d;
 Base& rb = d;
 // if Base::f() is virtual and Derived overrides it, Derived::f() will be called
 rb.f();  

纯虚函数是声明以=0结尾的虚函数:

A pure virtual function is a virtual function whose declaration ends in =0:

class Base {
  // ...
  virtual void f() = 0;
  // ...

纯虚函数隐式地将它定义为抽象的类(与在Java中使用关键字显式声明抽象类不同).抽象类不能被实例化.派生类需要覆盖/实现所有继承的纯虚函数.如果不这样做,它们也会变得抽象.

A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.

C++ 的一个有趣的特性"是一个类可以定义一个具有实现的纯虚函数.(有什么好处值得商榷.)

An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation. (What that's good for is debatable.)

请注意,C++11 为 deletedefault 关键字带来了新用法,它们看起来类似于纯虚函数的语法:

Note that C++11 brought a new use for the delete and default keywords which looks similar to the syntax of pure virtual functions:

my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;

参见这个问题和这个问题 有关此使用 deletedefault 的更多信息.

See this question and this one for more info on this use of delete and default.

这篇关于虚函数和纯虚函数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why does C++ compilation take so long?(为什么 C++ 编译需要这么长时间?)
Why is my program slow when looping over exactly 8192 elements?(为什么我的程序在循环 8192 个元素时很慢?)
C++ performance challenge: integer to std::string conversion(C++ 性能挑战:整数到 std::string 的转换)
Fast textfile reading in c++(在 C++ 中快速读取文本文件)
Is it better to use std::memcpy() or std::copy() in terms to performance?(就性能而言,使用 std::memcpy() 或 std::copy() 更好吗?)
Does the C++ standard mandate poor performance for iostreams, or am I just dealing with a poor implementation?(C++ 标准是否要求 iostreams 性能不佳,或者我只是在处理一个糟糕的实现?)