Home > Backend Development > C#.Net Tutorial > Must learn! Basic conditions for implementing polymorphic mechanism in C++

Must learn! Basic conditions for implementing polymorphic mechanism in C++

php是最好的语言
Release: 2018-07-24 14:11:02
Original
2195 people have browsed it

How to implement the polymorphic mechanism of C. The mechanism to implement running polymorphism is to add the virtual keyword before the function of the base class, rewrite the function in the derived class, and the runtime will be called according to the actual type of the object. corresponding function.

The implementation and principle of C polymorphism

The polymorphism of C can be summarized in one sentence: add the virtual keyword before the function of the base class, and add the virtual keyword before the derived function. If this function is overridden in the class, the corresponding function will be called according to the actual type of the object at runtime. If the object type is a derived class, the function of the derived class is called; if the object type is a base class, the function of the base class is called

1: The function declared with the virtual keyword is called a virtual function. The function must be a member function of the class.

2: Classes with virtual functions have a one-dimensional virtual function table called a virtual table. The object of the class has a virtual pointer pointing to the beginning of the virtual table. The virtual table corresponds to the class, and the virtual table pointer corresponds to the object.

3: Polymorphism is the multiple implementations of an interface and is the core of object-oriented. It is divided into class polymorphism and function polymorphism.

4: Polymorphism is implemented using virtual functions, combined with dynamic binding.

5: A pure virtual function is a virtual function plus = 0;

6: Abstract A class is a class that contains at least one pure virtual function.

Pure virtual function: virtual void fun()=0; that is, abstract class! This function must be implemented in the subclass, that is, there is a name first, no content, and the content is implemented in the derived class.

Let’s look at an example first

#include <iostream> #include <stdlib.h>using namespace std; 

class Father
{public:    void Face()
    {        cout << "Father&#39;s face" << endl;
    }    void Say()
    {        cout << "Father say hello" << endl;
    }
};class Son:public Father
{public:     
    void Say()
    {        cout << "Son say hello" << endl;
    }
};int main()
{
    Son son;
    Father *pFather=&son; // 隐式类型转换
    pFather->Say();    return 0;
}
Copy after login

The output result is:

Father say hello
Copy after login

We first define an object son of the Son class in the main() function, and then define A pointer variable pFather pointing to the Father class, and then use this variable to call pFather->Say(). It is estimated that many people tend to confuse this situation with the polymorphism of c, thinking that son is actually an object of the Son class, and should It calls Say of the Son class and outputs "Son say hello", but the result is not.

From a compilation point of view:

When the c compiler is compiling, it must determine each The address of the function (non-virtual function) called by the object. This is called early binding. When we assign the address of the object son of the Son class to pFather, the c compiler performs type conversion. At this time, the c compiler considers the variable pFather What is saved is the address of the Father object. When pFather->Say() is executed in the main function, what is called is of course the Say function of the Father object

From a memory perspective

Must learn! Basic conditions for implementing polymorphic mechanism in C++

The memory model of Son class object is as shown above

When we construct an object of Son class, we must first call the constructor of Father class to construct the object of Father class, and then call the constructor of Son class The function completes the construction of its own part, thus splicing out a complete Son class object. When we convert the Son class object to the Father type, the object is considered to be the upper half of the entire memory model of the original object, which is the "memory occupied by the Father object" in the above figure, then when we use the type conversion When the object pointer calls its method, of course it calls the method in the memory where it is located. Therefore, it is logical to output "Father Say hello".

As many people think, in the above code, we know that pFather actually points to an object of the Son class. We hope that the output result is the Say method of the son class. So when we think of achieving this result, You need to use virtual functions.

The previous output result is because the compiler has already determined the address of the function called by the object when compiling. To solve this problem, late binding must be used. When the compiler uses late binding, It will determine the type of the object and the correct calling function at runtime. To make the compiler adopt late binding, it is necessary to use the virtual keyword when declaring the function in the base class. We call such a function virtual Function, once a function is declared as virtual in the base class, then the function is virtual in all derived classes, without the need to explicitly declare it as virtual.

Change the code slightly and take a look at the running results

#include <iostream> #include <stdlib.h>using namespace std; 

class Father
{public:    void Face()
    {        cout << "Father&#39;s face" << endl;
    }    virtual void Say()
    {        cout << "Father say hello" << endl;
    }
};class Son:public Father
{public:     
    void Say()
    {        cout << "Son say hello" << endl;
    }
};int main()
{
    Son son;
    Father *pFather=&son; // 隐式类型转换
    pFather->Say();    return 0;
}
Copy after login

Running results:

Son say hello
Copy after login

We found that the result is "Son say hello", which means that the correct call is made based on the type of the object. function, then what happens behind the scenes when we declare Say() as virtual.

When the compiler is compiling, it finds that there are virtual functions in the Father class. At this time, the compiler will create a virtual table (i.e. vtable) for each class that contains a virtual function. This table is a one-dimensional array. , store the address of each virtual function in this array,

Must learn! Basic conditions for implementing polymorphic mechanism in C++

那么如何定位虚表呢?编译器另外还为每个对象提供了一个虚表指针(即vptr),这个指针指向了对象所属类的虚表,在程序运行时,根据对象的类型去初始化vptr,从而让vptr正确的指向了所属类的虚表,从而在调用虚函数的时候,能够找到正确的函数,对于第二段代码程序,由于pFather实际指向的对象类型是Son,因此vptr指向的Son类的vtable,当调用pFather->Son()时,根据虚表中的函数地址找到的就是Son类的Say()函数.

  正是由于每个对象调用的虚函数都是通过虚表指针来索引的,也就决定了虚表指针的正确初始化是非常重要的,换句话说,在虚表指针没有正确初始化之前,我们不能够去调用虚函数,那么虚表指针是在什么时候,或者什么地方初始化呢?

  答案是在构造函数中进行虚表的创建和虚表指针的初始化,在构造子类对象时,要先调用父类的构造函数,此时编译器只“看到了”父类,并不知道后面是否还有继承者,它初始化父类对象的虚表指针,该虚表指针指向父类的虚表,当执行子类的构造函数时,子类对象的虚表指针被初始化,指向自身的虚表。

  总结(基类有虚函数的):

  1:每一个类都有虚表

  2:虚表可以继承,如果子类没有重写虚函数,那么子类虚表中仍然会有该函数的地址,只不过这个地址指向的是基类的虚函数实现,如果基类有3个虚函数,那么基类的虚表中就有三项(虚函数地址),派生类也会虚表,至少有三项,如果重写了相应的虚函数,那么虚表中的地址就会改变,指向自身的虚函数实现,如果派生类有自己的虚函数,那么虚表中就会添加该项。

  3:派生类的虚表中虚地址的排列顺序和基类的虚表中虚函数地址排列顺序相同。

  这就是c++中的多态性,当c++编译器在编译的时候,发现Father类的Say()函数是虚函数,这个时候c++就会采用晚绑定技术,也就是编译时并不确定具体调用的函数,而是在运行时,依据对象的类型来确认调用的是哪一个函数,这种能力就叫做c++的多态性,我们没有在Say()函数前加virtual关键字时,c++编译器就确定了哪个函数被调用,这叫做早期绑定。

  c++的多态性就是通过晚绑定技术来实现的。

  c++的多态性用一句话概括就是:在基类的函数前加上virtual关键字,在派生类中重写该函数,运行时将会根据对象的实际类型来调用相应的函数,如果对象类型是派生类,就调用派生类的函数,如果对象类型是基类,就调用基类的函数。

  虚函数是在基类中定义的,目的是不确定它的派生类的具体行为,例如:

  定义一个基类:class Animal //动物,它的函数为breathe()

  再定义一个类class Fish //鱼。它的函数也为breathe()

  再定义一个类class Sheep //羊,它的函数也为breathe()

将Fish,Sheep定义成Animal的派生类,然而Fish与Sheep的breathe不一样,一个是在水中通过水来呼吸,一个是直接呼吸,所以基类不能确定该如何定义breathe,所以在基类中只定义了一个virtual breathe,它是一个空的虚函数,具体的函数在子类中分别定义,程序一般运行时,找到类,如果它有基类,再找到它的基类,最后运行的是基类中的函数,这时,它在基类中找到的是virtual标识的函数,它就会再回到子类中找同名函数,派生类也叫子类,基类也叫父类,这就是虚函数的产生,和类的多态性的体现。

  这里的多态性是指类的多态性。

  函数的多态性是指一个函数被定义成多个不同参数的函数。当你调用这个函数时,就会调用不同的同名函数。

一般情况下(不涉及虚函数),当我们用一个指针/引用调用一个函数的时候,被调用的函数是取决于这个指针/引用的类型。

当设计到多态性的时候,采用了虚函数和动态绑定,此时的调用就不会在编译时候确定而是在运行时确定。不在单独考虑指针/引用的类型而是看指针/引用的对象的类型来判断函数的调用,根据对象中虚指针指向的虚表中的函数的地址来确定调用哪个函数

现在我们看一个体现c++多态性的例子,看看输出结果:

#include <iostream> #include <stdlib.h>using namespace std; 

class CA 
{ 
public: 
    void f() 
    { 
        cout << "CA f()" << endl; 
    } 
    virtual void ff() 
    { 
        cout << "CA ff()" << endl; 
        f(); 
    } 
}; 

class CB : public CA 
{ 
public : 
    virtual void f() 
    { 
        cout << "CB f()" << endl; 
    } 
    void ff() 
    { 
        cout << "CB ff()" << endl; 
        f(); 
        CA::ff(); 
    } 
}; 
class CC : public CB 
{ 
public: 
    virtual void f() 
    { 
        cout << "C f()" << endl; 
    } 
}; 

int main() 
{ 
    CB b; 
    CA *ap = &b; 
    CC c; 
    CB &br = c; 
    CB *bp = &c; 

    ap->f(); 
    cout << endl;

    b.f(); 
    cout << endl;

    br.f(); 
    cout << endl;

    bp->f(); 
    cout << endl;

    ap->ff(); 
    cout << endl;

    bp->ff(); 
    cout << endl;    return 0; 
}
Copy after login

输出结果:

CA f()CB f()C f()C f()CB ff()CB f()CA ff()CA f()CB ff()C f()CA ff()CA f()
Copy after login

 相关推荐:

【c#教程】C# 多态性       

C# 多态性

C Video Tutorial_Free C Tutorial Online Learning

The above is the detailed content of Must learn! Basic conditions for implementing polymorphic mechanism in C++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template