// pointers to base class #include <iostream> using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class Rectangle: public Polygon { public: int area() { return width*height; } }; class Triangle: public Polygon { public: int area() { return width*height/2; } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = ▭ Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); //此处使用的是基类的函数 ppoly2->set_values (4,5); cout << rect.area() << ‘\n‘; //此处使用的是子类的函数调用,基类只能用基类的 cout << trgl.area() << ‘\n‘; return 0; }
虚成员vitual members
// virtual members #include <iostream> using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area () //虚函数 { return 0; } }; class Rectangle: public Polygon { public: int area () { return width * height; } }; class Triangle: public Polygon { public: int area () { return (width * height / 2); } }; int main () { Rectangle rect; Triangle trgl; Polygon poly; Polygon * ppoly1 = ▭ Polygon * ppoly2 = &trgl; Polygon * ppoly3 = &poly; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly3->set_values (4,5); cout << ppoly1->area() << ‘\n‘; //20 cout << ppoly2->area() << ‘\n‘; //10 cout << ppoly3->area() << ‘\n‘; //0 这种调用是一个默认,但是有可能使用不规范,忘记实现就不太好了 return 0; }
抽象类(abstract base class,ABC)就是类里定义了纯虚成员函数的类,纯虚函数只提供了接口,并没有具体实现。抽象类不能被实例化(不能创建对象),通常是作为基类供子类继承,子类中重写虚函数,实现具体的接口。在处理继承的问题上,ABC方法更系统性,更规范。
// pure virtual members can be called // from the abstract base class #include <iostream> using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area() =0; //纯虚函数,交给子类去实现 void printarea() { cout << this->area() << ‘\n‘; } }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } }; int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = ▭ Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); ppoly1->printarea(); //20 ppoly2->printarea(); //10 return 0; }
// dynamic allocation and polymorphism #include <iostream> using namespace std; class Polygon { protected: int width, height; public: Polygon (int a, int b) : width(a), height(b) {} virtual int area (void) =0; void printarea() { cout << this->area() << ‘\n‘; } }; class Rectangle: public Polygon { public: Rectangle(int a,int b) : Polygon(a,b) {} int area() { return width*height; } }; class Triangle: public Polygon { public: Triangle(int a,int b) : Polygon(a,b) {} int area() { return width*height/2; } }; int main () { Polygon * ppoly1 = new Rectangle (4,5); Polygon * ppoly2 = new Triangle (4,5); ppoly1->printarea(); ppoly2->printarea(); delete ppoly1; delete ppoly2; return 0; }
时间: 2024-11-10 08:01:21