青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品

posts - 297,  comments - 15,  trackbacks - 0
from http://en.wikipedia.org/wiki/Virtual_function

Virtual function

From Wikipedia, the free encyclopedia

Jump to: navigation, search

In object-oriented programming, a virtual function or virtual method is one whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP).

Contents

[hide]

[edit] Purpose

The concept of the virtual function solves the following problem:

In OOP when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class functions overridden by the derived class, a problem then arises when a derived object has been cast as the base class type. When a derived object is referred to as being of the base's type, the desired function call behavior is ambiguous.

The distinction between virtual and not virtual resolves this ambiguity. If the function in question is designated "virtual" in the base class then the derived class's function would be called (if it exists). If it is not virtual, the base class's function would be called.

Virtual functions overcome the problems with the type-field solution by allowing the programmer to declare functions in a base class that can be redefined in each derived class.

[edit] Example

For example, a base class Animal could have a virtual function eat. Subclass Fish would implement eat() differently than subclass Wolf, but you can invoke eat() on any class instance referred to as Animal, and get the eat() behavior of the specific subclass.

This allows a programmer to process a list of objects of class Animal, telling each in turn to eat (by calling eat()), with no knowledge of what kind of animal may be in the list. You also do not need to have knowledge of how each animal eats, or what the complete set of possible animal types might be.

[edit] C++

The following is an example in C++. Note that this example is not exception-safe. In particular, it may leak resources if new or vector::push_back throws an exception.

#include <iostream>
#include <vector>

using namespace std;
class Animal
{
public:
virtual void eat() const { cout << "I eat like a generic Animal." << endl; }
virtual ~Animal() {}
};

class Wolf : public Animal
{
public:
void eat() const { cout << "I eat like a wolf!" << endl; }
};

class Fish : public Animal
{
public:
void eat() const { cout << "I eat like a fish!" << endl; }
};

class GoldFish : public Fish
{
public:
void eat() const { cout << "I eat like a goldfish!" << endl; }
};


class OtherAnimal : public Animal
{
};

int main()
{
std::vector<Animal*> animals;
animals.push_back( new Animal() );
animals.push_back( new Wolf() );
animals.push_back( new Fish() );
animals.push_back( new GoldFish() );
animals.push_back( new OtherAnimal() );

for( std::vector<Animal*>::const_iterator it = animals.begin();
it != animals.end(); ++it)
{
(*it)->eat();
delete *it;
}

return 0;
}

Output with the virtual function Animal::eat():

I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

Output if Animal::eat() were not declared as virtual:

I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.
I eat like a generic Animal.

[edit] Java

In Java, all methods are by default "virtual functions." Only methods marked with the keyword final are non-virtual. The following is an example of virtual methods in Java:

import java.util.*;

public class Animal {
public void eat() { System.out.println("I eat like a generic Animal."); }

public static void main(String[] args) {
List<Animal> animals = new LinkedList<Animal>();

animals.add(new Animal());
animals.add(new Wolf());
animals.add(new Fish());
animals.add(new OtherAnimal());

for (Animal currentAnimal : animals) {
currentAnimal.eat();
}
}
}

public class Wolf extends Animal {
public void eat() { System.out.println("I eat like a wolf!"); }
}

public class Fish extends Animal {
public void eat() { System.out.println("I eat like a fish!"); }
}

public class OtherAnimal extends Animal {}

Output:

I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a generic Animal.

[edit] C#

In C#, a base class must provide the virtual modifier for any virtual method, and derived classes must provide the override modifier for any overriden method inherited from a base class. The following is an example in C#:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
public class Animal
{
public virtual void eat()
{
Console.WriteLine("I eat like a generic Animal.");
}
}

public class Wolf : Animal
{
public override void eat()
{
Console.WriteLine("I eat like a wolf!");
}
}

public class Fish : Animal
{
public override void eat()
{
Console.WriteLine("I eat like a fish!");
}
}

public class GoldFish : Fish
{
public override void eat()
{
Console.WriteLine("I eat like a goldfish!");
}
}

public class OtherAnimal : Animal
{
// eat() method is not overridden, so the base class method will be used.
}

class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();

animals.Add(new Animal());
animals.Add(new Wolf());
animals.Add(new Fish());
animals.Add(new GoldFish());
animals.Add(new OtherAnimal());

foreach (Animal currentAnimal in animals)
{
currentAnimal.eat();
}
}
}
}

Output:

I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

[edit] VB.NET

In VB.NET, a base class must provide the Overridable modifier for any virtual method, and derived classes may provide the optional Overrides modifier for any overriden method inherited from a base class (this prevents a warning from being issued). The following is an example in VB.NET:

Imports System
Imports System.Collections.Generic

Namespace ConsoleApplication1

Public Class Animal
Public Overridable Sub eat()
Console.WriteLine("I eat like a generic Animal.")
End Sub
End Class

Public Class Wolf
Inherits Animal
Public Overrides Sub eat()
Console.WriteLine("I eat like a wolf!")
End Sub
End Class

Public Class Fish
Inherits Animal
Public Overrides Sub eat()
Console.WriteLine("I eat like a fish!")
End Sub
End Class

Public Class Goldfish
Inherits Fish
Public Overrides Sub eat()
Console.WriteLine("I eat like a goldfish!")
End Sub
End Class

Public Class OtherAnimal
Inherits Animal
'eat() method is not overridden, so the base class method will be used.
End Class

Public Class Program
Shared Sub Main()
Dim animals As New List(Of Animal)
animals.Add(New Animal())
animals.Add(New Wolf())
animals.Add(New Fish())
animals.Add(New Goldfish())
animals.Add(New OtherAnimal())

For Each currentAnimal As Animal In animals
currentAnimal.eat()
Next
End Sub
End Class

End Namespace

Output:

I eat like a generic Animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.


[edit] Abstract classes and pure virtual functions

A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class that is not abstract. Classes containing pure virtual methods are termed "abstract;" they cannot be instantiated directly, and a subclass of an abstract class can only be instantiated directly if all inherited pure virtual methods have been implemented by that class or a parent class. Pure virtual methods typically have a declaration (signature) and no definition (implementation).

As an example, an abstract base class "MathSymbol" may provide a pure virtual function doOperation(), and derived classes "Plus" and "Minus" implement doOperation() to provide concrete implementations. Implementing doOperation() would not make sense in the "MathSymbol" class as "MathSymbol" is an abstract concept whose behaviour is defined solely for each given kind (subclass) of "MathSymbol". Similarly, a given subclass of "MathSymbol" would not be complete without an implementation of doOperation().

Although pure virtual methods typically have no implementation in the class that declares them, pure virtual methods in C++ are permitted to contain an implementation in their declaring class, providing fallback or default behaviour that a derived class can delegate to if appropriate.

Pure virtual functions are also used where the method declarations are being used to define an interface for which derived classes will supply all implementations. An abstract class serving as an interface contains only pure virtual functions, and no data members or ordinary methods. Use of purely abstract classes as interfaces works in C++ as it supports multiple inheritance. Because many OO languages do not support multiple inheritance they often provide a separate interface mechanism. This is seen in Java for example.

[edit] C++

In C++, pure virtual functions are declared using a special syntax [ = 0 ] as demonstrated below.

class Abstract {
public:
virtual void pure_virtual() = 0;
};

The pure virtual function declaration provides only the prototype of the method. Although an implementation of the pure virtual function is typically not provided in an abstract class, it may be included, although the definition may not be included at the point of declaration [1]. Every non-abstract child class is still required to override the method, but the implementation provided by the abstract class may be called in this way:

 void Abstract::pure_virtual() {
// do something
}

class Child : public Abstract {
virtual void pure_virtual(); // no longer abstract, this class may be
// instantiated.
};

void Child::pure_virtual() {
Abstract::pure_virtual(); // the implementation in the abstract class
// is executed
}

[edit] Java (and C#)

In Java (and C#), pure virtual methods are declared using the abstract keyword. Such a method cannot have a body. A class containing abstract methods (either directly, or inherited and not overridden) must itself be declared abstract. (But the converse is not true - an abstract class is not required to have any abstract methods.) An abstract class cannot be instantiated.

abstract class B {
abstract void a_pure_virtual_function();
}

Java also uses interfaces. All of the methods declared in an interface are implicitly abstract:

interface C {
void a_pure_virtual_function();
}

[edit] Behavior During Construction and Destruction

Languages differ in their behaviour while the constructor or destructor of an object is running. For some languages, notably C++, the virtual dispatching mechanism has different semantics during construction and destruction of an object. While it is recommended that virtual function calls in constructors should be avoided for C++ [2], in some other languages, for example Java and C#, the derived implementation can be called during construction and design patterns such as the Abstract Factory Pattern actively promote this usage in languages supporting the ability.

[edit] C++

#include <iostream>
#include <string>

using namespace std;

struct A
{
virtual string name() const { return "A"; }
virtual ~A() { cout << "Destructing " << name(); }
};

struct B : A
{
B() { cout << "Constructing " << name() << endl; }
virtual string name() const { return "B"; }
};

struct C : B
{
virtual string name() const { return "C"; }
};

int main()
{
C c; // Output: "Constructing B"

} // Output: "Destructing A"

[edit] Java

public class Base {
public int length() { return 0; }
public Base()
{
System.out.println("Constructing " + length());
}

static class Derived extends Base {
String name_;
public Derived(String name)
{
name_ = name != null ? name : ""; // Class invariant name_ is not null
}
public int length() { return name_.length(); } // Assume name_ is not null
}

public static void main(String[] args)
{
new Derived("Ooops"); // NullPointerException, Derived.name_ has not been assigned to yet
}
}

This is because the constructor of Base is executed before the constructor of Derived. As the constructor of Base calls length(), a null pointer exception is thrown.

[edit] Virtual destructors

Object-oriented languages typically manage memory allocation and deallocation automatically when objects are created and destroyed, however some object-oriented languages allow a custom destructor method to be implemented if desired. One such language is C++, and as illustrated in the following example, it is important for a C++ base class to have a virtual destructor to ensure that the destructor from the most derived class will always be called.

In the example below having no virtual destructor, while deleting an instance of class B will correctly call destructors for both B and A if the object is deleted as an instance of B, an instance of B deleted via a pointer to its base class A will produce undefined behaviour.[3] On many implementations, the destructor for B will not be called in this situation.

 #include <iostream>
using namespace std;

class A
{
public:

A() { }
~A() { cout << "Destroy A" << endl; }
};

class B : public A
{
public:

B() { }
~B() { cout << "Destroy B" << endl; }
};

int main()
{
A* b1 = new B;
B* b2 = new B;

delete b1; // According to the C++ standard,
// the behaviour of this is undefined.
// Usually, only ~A() is called though b1 is an instance
// of class B because ~A() is not declared virtual.
delete b2; // Calls destructors ~B() and ~A()

return 0;
}

Possible output:

Destroy A
Destroy B
Destroy A

Correctly declaring the destructor for class A as virtual ~A() will ensure that the destructor for class B is called in both cases with the example above.

[edit] See also

[edit] References

  1. ^ Standard C++ 98 - 10.4/2
  2. ^ Meyers, Scott (June 6, 2005). "Never Call Virtual Functions during Construction or Destruction". http://www.artima.com/cppsource/nevercall.html. 
  3. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §5.3.5 Delete [expr.delete] para. 3


posted on 2009-04-19 23:32 chatler 閱讀(873) 評論(0)  編輯 收藏 引用 所屬分類: C++_BASIS
<2009年12月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用鏈接

留言簿(10)

隨筆分類(307)

隨筆檔案(297)

algorithm

Books_Free_Online

C++

database

Linux

Linux shell

linux socket

misce

  • cloudward
  • 感覺這個博客還是不錯,雖然做的東西和我不大相關,覺得看看還是有好處的

network

OSS

  • Google Android
  • Android is a software stack for mobile devices that includes an operating system, middleware and key applications. This early look at the Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
  • os161 file list

overall

搜索

  •  

最新評論

閱讀排行榜

評論排行榜

青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品
  • <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            欧美在线影院在线视频| 欧美成人综合| 欧美视频导航| 亚洲国产精品va在线观看黑人| 久久综合国产精品台湾中文娱乐网 | 欧美日韩精品在线观看| 一区二区三区国产精华| 欧美一区二区三区久久精品茉莉花 | 久久中文欧美| 免费国产自线拍一欧美视频| 一区二区免费在线观看| 国产精品美女主播在线观看纯欲| 性久久久久久久久| 亚洲精品久久久久久久久| 久久久无码精品亚洲日韩按摩| 欧美一区二区视频在线观看| 久久综合伊人| 亚洲综合色婷婷| 亚洲国产高清一区二区三区| 欧美日韩午夜视频在线观看| 久久精品国产v日韩v亚洲| 91久久极品少妇xxxxⅹ软件| 亚洲欧美另类中文字幕| 久久久久国产精品人| 日韩视频免费| 欧美承认网站| 在线视频精品一| 91久久视频| 亚洲一区二区黄色| 一区二区三区日韩在线观看| 亚洲中字在线| 一区二区不卡在线视频 午夜欧美不卡在 | 黄色影院成人| 国产精品99免费看 | 美玉足脚交一区二区三区图片| 欧美激情在线播放| 免费国产一区二区| 亚洲天堂成人| 亚洲天堂av综合网| 快播亚洲色图| 久久久亚洲国产天美传媒修理工 | 国产亚洲综合精品| 欧美日韩在线第一页| 好男人免费精品视频| 一区二区三区.www| 欧美午夜精品久久久久久浪潮| 国产综合色产| 精品成人一区二区| 亚洲欧美日本伦理| 亚洲国产日韩欧美一区二区三区| 午夜视频在线观看一区二区| 欧美日韩一区二区三区四区在线观看 | 亚洲国产精品久久久久| 性色av一区二区三区| 欧美一区二区三区久久精品| 亚洲精品国产精品国自产在线| 亚洲一区二区av电影| 欧美午夜精品久久久久免费视| 激情久久综合| 久久久久在线观看| 亚洲免费在线电影| 国产精品www色诱视频| 一区二区久久| 亚洲精品在线观| 日韩网站在线观看| 欧美大片免费久久精品三p| 欧美精品福利在线| 亚洲一区二区三区高清不卡| 美国成人毛片| 久久亚洲综合色| 欧美激情视频给我| 亚洲国产日韩欧美一区二区三区| 亚洲欧洲精品一区| 亚洲一区二区三区四区五区午夜| 亚洲激情校园春色| 欧美国产一区视频在线观看| 国产精品日韩高清| 在线观看国产一区二区| 99视频一区| 久久精品日产第一区二区| 免费亚洲视频| 欧美a级在线| 国产婷婷色一区二区三区在线| 狠狠干综合网| 免费人成精品欧美精品| 免费观看亚洲视频大全| 亚洲精品五月天| 久久综合综合久久综合| 麻豆freexxxx性91精品| 亚洲免费观看视频| 久久躁日日躁aaaaxxxx| 久久国产精品第一页| 亚洲国产精品成人久久综合一区| 亚洲黄色一区| 国产精品亚洲产品| 欧美激情视频在线播放| 欧美视频精品在线| 欧美成人午夜激情| 午夜日韩在线| 亚洲精品一区二区三区福利| 夜久久久久久| 六月天综合网| 一区二区三区日韩| 久久精品91久久久久久再现| 亚洲精品乱码久久久久久| 亚洲视频一区| 亚洲欧洲日本专区| 欧美与欧洲交xxxx免费观看| 国产精品久久久久久久app| 亚洲精品乱码久久久久久日本蜜臀 | 香蕉久久夜色精品国产使用方法| 在线日韩日本国产亚洲| 久久精品国产综合| 亚洲无玛一区| 在线激情影院一区| 91久久久久久久久| 国产一区久久| 中文日韩欧美| 亚洲精品乱码久久久久久久久| 亚洲欧美成人综合| 一区二区三区精密机械公司| 久久视频在线看| 欧美亚洲在线观看| 欧美另类视频| 一区二区三区精品国产| 久久综合伊人77777尤物| 亚久久调教视频| 亚洲欧美日韩视频一区| 欧美黄色免费网站| 久久久久久久欧美精品| 久久综合网hezyo| 久久国产精品黑丝| 国产精品乱码一区二三区小蝌蚪| 亚洲精品久久久久久下一站| 亚洲国产电影| 免费不卡亚洲欧美| 欧美国产精品一区| 亚洲国产午夜| 裸体一区二区三区| 欧美黑人一区二区三区| 亚洲国产裸拍裸体视频在线观看乱了中文 | 亚洲国产女人aaa毛片在线| 国产一区二区三区四区在线观看 | 亚洲一级片在线看| 亚洲一区二区黄色| 欧美日韩日本视频| 在线视频欧美日韩精品| 亚洲欧美在线另类| 久久久www| 久久综合色8888| **性色生活片久久毛片| 免费不卡视频| 9色精品在线| 国产一区视频在线观看免费| 欧美一区二视频| 嫩草国产精品入口| 国产精品久久国产三级国电话系列| 亚洲美女视频在线观看| 亚洲欧美日韩国产精品| 国产日韩欧美日韩| 久久婷婷国产综合尤物精品| 欧美成人激情视频| 一区二区三区久久精品| 国产精品一二| 蜜臀久久久99精品久久久久久| 狠狠入ady亚洲精品经典电影| 欧美一区二区三区喷汁尤物| 理论片一区二区在线| 亚洲精品中文在线| 国产美女精品视频免费观看| 米奇777超碰欧美日韩亚洲| 黄色av成人| 久久久久久尹人网香蕉| 欧美第十八页| 宅男噜噜噜66一区二区66| 国产日韩精品一区二区浪潮av| 免费观看一区| 一区二区日本视频| 韩国av一区二区三区四区| 欧美国产精品一区| 午夜精品久久久久久久白皮肤| 欧美jizzhd精品欧美巨大免费| 日韩视频免费观看高清在线视频 | 日韩亚洲一区在线播放| 久久成人人人人精品欧| 亚洲精品乱码久久久久久蜜桃91| 欧美中文字幕在线播放| 日韩一级黄色大片| 免费久久99精品国产| 亚洲无亚洲人成网站77777| 黄色在线成人| 国产精品视频最多的网站| 免费看成人av| 欧美在线999| 亚洲一区www| 日韩午夜视频在线观看| 亚洲第一网站| 亚洲国产精品va在线看黑人动漫 | 亚洲激情一区| 极品少妇一区二区三区|