[C++] Polymorphism

HW Yang
1 min readOct 15, 2019

--

http://teddy-chen-tw.blogspot.com/2012/01/3polymorphism.html
http://monkeycoding.com/?p=936

#include &ltiostream&gt
using namespace std;

class animal {
public:
virtual void f1() = 0;
virtual void f2() = 0;
virtual void f3() = 0;
};

class cat : public animal {
public:
void f1() {
cout << "cat's f1" << endl;
}

void f2() {
cout << "cat's f2" << endl;
}

void f3() {
cout << "cat's f3" << endl;
}
};

class dog : public animal {
public:
void f1() {
cout << "dog's f1" << endl;
}

void f2() {
cout << "dog's f2" << endl;
}

void f3() {
cout << "dog's f3" << endl;
}
};


int main() {
animal *a = new dog;

a->f1();
}

C 版本的多型

#include <stdio.h>
#include <string.h>

struct animal {
void (*f1)(void);
void (*f2)(void);
void (*f3)(void);
};


void dog_f1(void) { printf("dog's f1\n"); }
void dog_f2(void) { printf("dog's f2\n"); }
void dog_f3(void) { printf("dog's f3\n"); }

void cat_f1(void) { printf("cat's f1\n"); }
void cat_f2(void) { printf("cat's f2\n"); }
void cat_f3(void) { printf("cat's f3\n"); }

struct animal dog = {
dog_f1,
dog_f2,
dog_f3,
};

struct animal cat = {
cat_f1,
cat_f2,
cat_f3,
};

int main(int argc, char **argv)
{
struct animal *a;

if (strcmp(argv[1], "dog") == 0)
a = &dog;
else if (strcmp(argv[1], "cat") == 0)
a = &cat;

a->f1();

return 0;
}

--

--

HW Yang
HW Yang

No responses yet