Lesson 52nd abstract classes and interfaces in C + +

Source: Internet
Author: User

What is an abstract class?

Problem:

Does the shape class need to exist?

Abstract classes are required to be supported in object-oriented.

An exploration of abstract classes:

The compilation results are as follows:

Refine the example:

1#include <iostream>2#include <string>3 4 using namespacestd;5 6 classShape7 {8  Public:9     Virtual DoubleArea () =0;Ten }; One  A classRect: PublicShape - { -     intMa; the     intMB; -  Public: -Rect (intAintb) -     { +Ma =A; -MB =b; +     } A     DoubleArea () at     { -         returnMA *MB; -     } - }; -  - classCircle: PublicShape in { -     intMr; to  Public: +Circle (intR) -     { theMr =R; *     } $     DoubleArea ()Panax Notoginseng     { -         return 3.14* Mr *Mr; the     } + }; A  the voidArea (shape*p) + { -     Doubler = p->Area (); $      $cout <<"r ="<< R <<Endl; - } -  the intMain () - {WuyiRect rect (1,2); theCircle Circle (Ten); -      WuArea (&rect); -Area (&circle); About      $     return 0; -}

The pure virtual function is to be overridden in a subclass.

Operation Result:

Abstract classes cannot define objects, but abstract classes can define pointers.

Abstract classes and pure virtual functions:

Interface:

C + + does not have a real interface, no specific syntax support, the following language C #, Java has interfaces.

Interface Example:

1#include <iostream>2#include <string>3 4 using namespacestd;5 6 classChannel7 {8  Public:9     Virtual BOOLOpen () =0;Ten     Virtual voidClose () =0; One     Virtual BOOLSendChar* BUF,intLen) =0; A     Virtual intReceiveChar* BUF,intLen) =0; - }; -  the intMain () - { -     return 0; -}

We only define the function, which is an interface.

Summary:

Lesson 52nd abstract classes and interfaces in C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.