: , () . virtual, , . , , , , virtual .
( , ) , . , . .
: , . , , vmtbl(virtual method table ) . . , . , .
:
// 33
/* */
#include <iostream.h>
#include <conio.h>
class Base {
public:
virtual void who() { //
cout << "Base\n";
}
};
class First: public Base {
public:
void who() { // who() First
cout << "First\n";
}
};
class Second: public Base {
public:
void who() { // who() Second
cout << "Second\n";
}
};
/* a */
void show_who(Base &r) {
r.who();
}
int main() {
Base base_obj;
Base* pb;
pb=&base_obj;
pb->who(); //base_obj.who()
First first_obj;
pb=&first_obj;
pb->who(); //first_obj.who()
Second second_obj;
pb=&second_obj;
pb->who(); //second_obj.who()
show_who(base_obj); // Base's who()
show_who(first_obj); // First's who()
show_who(second_obj); // Second's who()
while(!kbhit());
return 0;
}
: Base
First
Second
Base
First
Second
, List:
|
|
/*,
*/
#include <iostream.h>// 34
#include <stdlib.h>
class List {
public:
List *head; //
List *tail;//
List *next;//
int num; //
List () { head = tail = next = NULL; }
virtual void store(int i) = 0;/* */
virtual int retrieve() = 0;/* */
};
//
class Queue: public List {
public:
void store(int i);
int retrieve();
queue operator+(int i) { store(i); return *this; }
/* */
int operator --(int unused) { return retrieve(); } };
void Queue::store(int i) {
list *item;
item = new Queue;
if(!item) {
cout << " \n";
exit(1); }
item -> num = i;
//
if(tail) tail -> next = item;
tail = item;
item -> next = NULL;
if(!head) head = tail;
}
int Queue::retrieve() {
int i;
List *p;
if(!head) {cout << " \n";return 0; }
//
i = head -> num;
p = head;
head = head -> next;
delete p;
return i;
}
class Stack: public List {/* */
public:
void store(int i);
int retrieve();
stack operator+(int i) { store(i); return *this; }
int operator --(int unused) { return retrieve(); }
};
void stack::store(int i) {
List *item;
item = new Stack;
if(!item) {
cout << " \n";
exit(1);}
item -> num = i;
// ,
if(head) item -> next = head;
head = item;
if(!tail) tail = head;
}
int Stack::retrieve() {
int i;
list *p;
if(!head) {cout << " \n";
return 0; }
//
i = head -> num;
p = head;
head = head -> next;
delete p;
return i;
}
int main() {
List *p;
//
Queue q_ob;
p = &q_ob; //
q_ob + 1;
q_ob + 2;
q_ob + 3;
cout << ": ";
cout << q_ob --;// 1
cout << q_ob --;// 2
cout << q_ob --;// 3
cout << '\n';
//
Stack s_ob;
p = &s_ob; //
s_ob + 1;
s_ob + 2;
s_ob + 3;
cout << ": ";
cout << s_ob --;// 3
cout << s_ob --;// 2
cout << s_ob --;// 1
cout << '\n';
return 0;
}
, ( ).