赞
踩
#include <iostream> #include <cstdio> #include <cstdlib> #include <queue> #include <stack> #include <algorithm> #include <string> #include <map> #include <set> #include <vector> using namespace std; class Animal { public : Animal(string name):name(name){} virtual void run() { cout << "I don't kown how to run" << endl; } private: string name; }; class Cat : public Animal { public : Cat(string name):Animal(name){} void run() override final{ cout << "I can run with four legs" << endl; } }; class People : public Animal { public : People(string name):Animal(name){} void run() override final{ cout << "I can run with two legs" << endl; } }; class Bat : public Animal { public : Bat(string name) : Animal(name){} void run() override final{ cout << "I can fly" << endl; } }; int main(){ #define MAX_N 10 srand(time(0)); Animal **zoo = new Animal*[MAX_N]; for (int i = 0; i < MAX_N; i++) { switch(rand() % 3) { case 0: zoo[i] = new Cat("cat"); break; case 1: zoo[i] = new People("people"); break; case 2: zoo[i] = new Bat("bat"); break; } } for (int i = 0; i < MAX_N; i++) zoo[i]->run(); return 0; }
I can run with four legs
I can run with four legs
I can fly
I can fly
I can fly
I can run with four legs
I can run with four legs
I can run with two legs
I can fly
I can run with two legs
#include <iostream> #include <cstdio> #include <cstdlib> #include <queue> #include <stack> #include <algorithm> #include <string> #include <map> #include <set> #include <vector> using namespace std; class A { public : virtual void say() { cout << "Class A say" << endl; } virtual void run() { cout << "Class A run" << endl; } }; class B : public A { public : void say() override final{ cout << "Class B say" << endl; } }; class C : public A { public : void run() override final{ cout << "Class C run" << endl; } }; #define TEST(a) test(a, #a) void test(A &a, string class_name) { cout << "Object " << class_name << endl; a.say(); a.run(); cout << "===========" << endl << endl; return; } int main(){ A a; B b; C c; TEST(a); TEST(b); TEST(c); //注意思考此处 ((void **)(&b))[0] = ((void **)(&a))[0]; TEST(b); return 0; }
Object a Class A say Class A run =========== Object b Class B say Class A run =========== Object c Class A say Class C run =========== Object b Class A say Class A run ===========
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。