動態繫結(dynamic binding)寫法
#include <iostream>
using namespace std;
class mammal {
public:
mammal () { cout << "Class mammal constructor\n"; }
virtual ~mammal () { cout << "Class mammal destructor\n"; }
void virtual speak() const { cout << "This is mammal's speaking\n"; }
};
class dog: public mammal {
public:
dog () { cout << "Class dog constructor\n"; }
virtual ~dog () { cout << "Class dog destructor\n"; }
void virtual speak() const { cout << "This is dog's speaking\n"; }
};
int main() {
mammal *pm[2];
// mammal
pm[0] = new mammal;
pm[0]->speak();
delete pm[0];
// dog
pm[1] = new dog;
pm[1]->speak();
delete pm[1];
return 0;
};
#include <iostream>
using namespace std;
class mammal {
public:
mammal () { cout << "Class mammal constructor\n"; }
virtual ~mammal () { cout << "Class mammal destructor\n"; }
void virtual speak() const { cout << "This is mammal's speaking\n"; }
void method01() const { cout << "This is method01\n"; }
void virtual method02() const { cout << "This is method02\n"; }
};
class dog: public mammal {
public:
dog () { cout << "Class dog constructor\n"; }
virtual ~dog () { cout << "Class dog destructor\n"; }
void virtual speak() const { cout << "This is dog's speaking\n"; }
void method02() const { cout << "This is method02\n"; }
};
int main() {
mammal *pm[2];
// mammal
pm[0] = new mammal;
pm[0]->speak();
pm[0]->method01();
delete pm[0];
// dog
pm[1] = new dog;
pm[1]->speak();
pm[1]->method01();
pm[1]->method02();
delete pm[1];
return 0;
};
#include <iostream>
using namespace std;
class mammal {
public:
mammal () { cout << "Class mammal constructor\n"; }
virtual ~mammal () { cout << "Class mammal destructor\n"; }
void virtual speak() const { cout << "This is mammal's speaking\n"; }
void method01() const { cout << "This is method01\n"; }
};
class dog: public mammal {
public:
dog () { cout << "Class dog constructor\n"; }
virtual ~dog () { cout << "Class dog destructor\n"; }
void virtual speak() const { cout << "This is dog's speaking\n"; }
void method02() const { cout << "This is method02\n"; }
};
int main() {
mammal *pm[2];
// mammal
pm[0] = new mammal;
pm[0]->speak();
pm[0]->method01();
delete pm[0];
// dog
pm[1] = new dog;
pm[1]->speak();
pm[1]->method01();
static_cast
delete pm[1];
return 0;
};
0 意見:
張貼留言