Blog Archive

Wednesday, October 31, 2018

c++ programming tutorial

http://www.newthinktank.com/2014/11/c-programming-tutorial/

C++中的虚函数的作用主要是实现了多态的机制。关于多态,简而言之就是用父类型别的指针指向其子类的实例,然后通过父类的指针调用实际子类的成员函数。这种技术可以让父类的指针有“多种形态”,这是一种泛型技术。所谓泛型技术,说白了就是试图使用不变的代码来实现可变的算法。比如:模板技术,RTTI技术,虚函数技术,要么是试图做到在编译时决议,要么试图做到运行时决议
---------------------
作者:haoel
来源:CSDN
原文:https://blog.csdn.net/haoel/article/details/1948051
版权声明:本文为博主原创文章,转载请附上博文链接!

代码:

#include <iostream>
using namespace std;

// Virtual Methods and Polymorphism
// Polymorpism allows you to treat subclasses as their superclass and yet
// call the correct overwritten methods in the subclass automatically

class Animal{
public:
void getFamily() { cout << "We are Animals" << endl; }

// When we define a method as virtual we know that Animal
// will be a base class that may have this method overwritten
virtual void getClass() { cout << "I'm an Animal" << endl; }
};

class Dog : public Animal{
public:
void getClass() { cout << "I'm a Dog" << endl; }

};

class GermanShepard : public Dog{
public:
void getClass() { cout << "I'm a German Shepard" << endl; }
void getDerived() { cout << "I'm an Animal and Dog" << endl; }

};

void whatClassAreYou(Animal *animal){
animal -> getClass();
}

int main(){

Animal *animal = new Animal;
Dog *dog = new Dog;

// If a method is marked virtual or not doesn't matter if we call the method
// directly from the object
animal->getClass();
dog->getClass();

// If getClass is not marked as virtual outside functions won't look for
// overwritten methods in subclasses however
whatClassAreYou(animal);
whatClassAreYou(dog);

Dog spot;
GermanShepard max;



// A base class can call derived class methods as long as they exist
// in the base class
Animal* ptrDog = &spot;
Animal* ptrGShepard = &max;

// Call the method not overwritten in the super class Animal
ptrDog -> getFamily();

// Since getClass was overwritten in Dog call the Dog version
ptrDog -> getClass();

// Call to the super class
ptrGShepard -> getFamily();

// Call to the overwritten GermanShepard version
ptrGShepard -> getClass();
        max.getDerived(); // OK
//ptrGShepard -> getDerived(); // error
GermanShepard* ptrGShepard2 = & max;
        ptrGShepard2 -> getDerived(); // OK
return 0;
}

No comments:

Post a Comment