A common method of using structs in Android source code

Source: Internet
Author: User

See examples directly:

#include <iostream>#include<stdlib.h>using namespacestd;structbase{intBA; intBB; voidPrintb () {cout<<"Base Print"<<Endl; }};structa{structBase B; intAA; voidPrintA () {cout<<"A Print"<<Endl; }};intMain () {//pointer of type a    structAA; //create an object by type aA = (structA *) Calloc (1,sizeof(*a)); A->b.ba = A; A-&GT;B.BB = the; A-&GT;AA = $; //To change it to a base type variable    structBase *bp = & (a->b); BP-Printb (); cout<<bp->ba<<"  "<<bp->bb<<Endl; //the above are common, but note here: convert them directly back to type a    structA *ap = (structA) BP; AP-PrintA (); cout<<ap->b.ba<<"  "<<ap->b.bb<<"  "<<ap->aa<<Endl;}

Output:

Base Print
12 34
A Print
12 34 65

Note that the base type variable must be the first member variable of a!

This usage is often used in the Android source Hal, where the base can be used as a canonical parameter for a function interface, but another type is passed in as a base type in the function, which can then be cast to the original type a processing. This also allows you to extend the base type, which feels somewhat similar to the effect of inheritance.

A common method of using structs in Android source code

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.