虚函数的动态绑定

#include <iostream>
#include <stdlib.h>
using namespace std;
enum note {middleC, Cshape, Cflat};


class Instrument {
public:
virtual void play(note) const {
cout << "Instrument::paly" << endl;
}
virtual char* what() const {
return "Instrument";
}
virtual void adjust(int) {}
};


class Wind : public Instrument {
public:
void play(note) const {
cout << "Wind::play" << endl;
}
char* what() const {return "Wind";}
void adjust(int) {}
};


class Percussion : public Instrument {
public:
void play(note) const {
cout << "Percussion::play" << endl;
}
char* what() const {return "Percussion";}
void adjust(int) {}
};


void tune(Instrument& i) {
i.play(middleC);//通过引用取对象的地址传给此函数
}


void f(Instrument* i) {
i->adjust(1);//通过指针显式地取对象的地址传给此函数
}


Instrument* A[] = {
new Wind,
new Percussion,
};


int main() {
Wind flute;
Percussion drum;
tune(flute);//此处需要传入对象本身
tune(drum);//此处需要传入对象本身
f(&drum);//此处需要传入对象的地址
system("pause");
return 0;
}

你可能感兴趣的:(C++,虚函数,动态绑定)