📄 virtual.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head> <meta name="generator" content= "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org"> <title>virtual</title> <link href="../cppreference.css" rel="stylesheet" type="text/css"></head><body><table> <tr> <td> <div class="body-content"> <div class="header-box"> <a href="../index.html">cppreference.com</a> > <a href= "index.html">C/C++ Keywords</a> > <a href= "virtual.html">virtual</a> </div> <div class="name-format"> virtual </div> <div class="syntax-name-format"> Syntax: </div> <pre class="syntax-box"> virtual return-type name( parameter-list ); virtual return-type name( parameter-list ) = 0;</pre> <p>The virtual keyword can be used to create virtual functions, which can be overridden by derived classes.</p> <ul> <li>A virtual function indicates that a function can be overridden in a subclass, and that the overridden function will actually be used.</li> <li>When a base object pointer points to a derived object that contains a virtual function, the decision about which version of that function to call is based on the type of object pointed to by the pointer, and this process happens at runtime.</li> <li>A base object can point to different derived objects and have different versions of the virtual function run.</li> </ul> <p>If the function is specified as a pure virtual function (denoted by the = 0), it must be overridden by a derived class.</p> <div class="related-examples-format"> Example code: </div> <div class="related-examples"> <p>For example, the following code snippet shows how a child class can override a virtual method of its parent, and how a non-virtual method in the parent cannot be overridden:</p> <pre class="example-code">class Base {public: void nonVirtualFunc() { cout << "Base: non-virtual function" << endl; } virtual void virtualFunc() { cout << "Base: virtual function" << endl; }}; class Child : public Base {public: void nonVirtualFunc() { cout << "Child: non-virtual function" << endl; } void virtualFunc() { cout << "Child: virtual function" << endl; }}; int main() { Base* basePointer = new Child(); basePointer->nonVirtualFunc(); basePointer->virtualFunc(); return 0;} </pre> <p>When run, the above code displays:</p> <pre class="example-code">Base: non-virtual functionChild: virtual function </pre> </div> <div class="related-name-format"> Related topics: </div> <div class="related-content"> <a href="class.html">class</a> </div> </div> </td> </tr> </table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -