C + + class templates

Source: Internet
Author: User

The code is as follows:

#include <iostream>#include<cstdlib>using namespaceStd;typedefstructTstudent//complete definition of struct body{    intnId; floatFGpa;} Tstudent;template<classT>//template classclasscstroe{ Public: Cstroe (); //constructor FunctionT &getelem ();//return Reference    voidPutelem (ConstT &x);//Delivery type ReferencePrivate: T item; //Data    BOOLHavevalue;//Control};template<classT> Cstroe<t>::cstroe (): Havevalue (false){}//Constructor InitializationTemplate<classT> t& Cstroe<t>::getelem ()//return Reference{    ////control Switch status    if(!havevalue) {cout<<"No Item present!"<<Endl; //exit (1);    }    returnitem;} Template<classT>voidCstroe<t>::p Utelem (ConstT &trec)//Reference (alias) delivery{Havevalue=true;//Setting the switch statusItem =trec;//}intMain () {//Plastic Examplecstroe<int> nstu1,nstu2;//template classNstu1.putelem (3); Nstu2.putelem (-7); cout<<nstu1.getelem () <<""<<nstu2.getelem () <<Endl; //example of structure typeTstudent tg={ +, at};//Structural BodyCstroe<Tstudent> tS3;//template classTs3.putelem (TG); cout<<"The student ID is"<<ts3.getelem () .nid<<"\ t"<<"Gpa is"<<ts3.getelem () .fgpa<<Endl; //Double Typecstroe<Double>Dstu; cout<<"Retrieving object D ..."; cout<<dstu.getelem () <<Endl;    GetChar (); return 0;}

Results:

CFree5 Value Analysis:

Note: Exit (1) in the code snippet, which can be used to indicate the cause of the termination of the program and be accepted by the operating system

Analysis conclusion: Using class template Users can define a pattern for a class so that some data in a class, parameters of a function member, a return value, or a local variable can take any type.

C + + class templates

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.