C + + code reuse-student (learning notes)

Source: Internet
Author: User

Code reuse in the 14th chapter of--c++
    • Classes that contain object members
14.1.1 Valarray Introduction

Header filevalarray
Supported Features:

    1. Adds the values of the elements used in the array
    2. Find operations such as maximum and minimum values

Declaring an object with the Valarray class

valarray < int > q_values;valarray < double > weights;

Code snippets that use constructors

valarray< double > gpa[5] = {3.4,5.6,7.8,5.3,1.2};valarray < double > v1;valarray < int > v2(8);// an array of 8 int elementsvalarray < int > v3(10,8);//an array of 8 int elements;                          //each set to 10;valarray < double > v4(gpa,4)//an array of 4 double elements                          //initialized to the first 4 elements of gpa;

Design of the 14.1.2students class

typedef std::valarray< double > ArrayDb;

    • typedefthe role of join: In the future code can be used to represent arraydb

Note Keyword Explicit

explicit student(const std::string & s):name(s),scores(){}explicit student(int n):name(),scores(n){}

The code above uses explicit to turn off implicit conversions

    • Use explicit to prevent implicit conversions of parameter number constructors, root cause: Errors in the compilation phase are better than errors at run time
Order of initialization
    • The order in which items are initialized is the order in which they are declared
      student(const char* str,const double* pd ,int n):scores(pd,n),name(str){}
      Based on the above principle: the name member is initialized first, because in the definition of the class he is first declared, so in this case the initialization order is not important, but if the value of one member is part of the initialization of another member, the order of initialization is very important.
function implementation
1 #include2 usingStd::ostream;3 usingStd::endl;4 usingstd::cout;5 usingStd::istream;6 usingSTD::string;7 8 //Public Methods9 DoubleStudent::average ()ConstTen { One     if(Scores.size () >0) A     { -         returnScores.sum ()/scores.size (); -     } the     Else -     { -         return 0; -     } + } - Const string& Student::name ()Const + { A     returnname; at } - Double& Student::operator[](inti) - { -     returnScores[i]; - } -  in DoubleStudent::operator[](intIConst - { to     returnScores[i]; + } - //Private Methods theOstream & Student::arr_out (std::ostream & OS)Const * { $     inti;Panax Notoginseng     intlim=scores.size (); -     if(lim>0) the     { +          for(i=0;i<<<" "; A             if(i%5==4)//one line of 5 elements theos<<<<"Empty Array"; +         returnos; -     } $ } $ //friend function -IStream &operator>> (IStream & is,student&Stu) - { the      is>>Stu.name; -     return  is;Wuyi } the //using the string friend function -IStream & Getline (IStream & is, Student &Stu) Wu { -      is>>Stu.name; About     return  is; $ } -Ostream &operator<< (Ostream & OS,Conststudent&Stu) - { -os<<"scores for:"<<<": \ n"; A     //use private methods for output of scores + stu.arr_out (OS); the     returnos; -}

 

Description

    • Problem one: using an interface that contains objects

Because the interfaces of the contained objects are not common, the interface here, my understanding is the function that contains the class that the object belongs to, how to use it? We can use it through the class method (here is the Studnet class), such as the code:

double student::average()const{if(scores.size()>0){return scores.sum()/scores.size();}else{return 0;}}

Student calls its scoped method average (), average can access student's private data, that is, scores object, scores is an object of Valarray, and can naturally invoke its internal methods

    1. Size ()
    2. SUM ()

    • Question two:the class method that scores calls itself
double & student::operator [](int i){return scores[i];}

Scores[i] will call the overloaded methods in the Valarray class directly:valarray<douoble>::operator[]()

    • Question three: about the output of the member function scores

First, we can first look at the output of the member function name, as follows:

ostream & operator<<(ostream & os,const student& stu){os<<"scores for: "<< stu.name<<":\n";return os;}

The reason why you can do this is because Stu.name is an object of string, so it calls the operator << () overloaded function inside string we can do the same with scores? Of course, unless the Valarray also contains the operator<< () function, unfortunately, Valarray does not have this function

    • Define private helper functions (add function to private data of Class)
    • Std::ostream & Arr_out (std::ostream& os) const;
ostream & student::arr_out(std::ostream & os)const{int i;int lim=scores.size();if(lim>0){for(i=0;i< lim;i++){os<< scores[i]<< " ";if(i%5==4)os << endl;}if(i%5!=0)os << endl;}    else{os<<"empty array ";return os;}}
Main function
    • An array of 3 objects containing 5 scores per object
1 #include2#include"student.h"3 4 usingstd::cin;5 usingstd::cout;6 usingStd::endl;7 void Set(Student & SA,intn);8 //Two Constants9 Const intpupils=3;Ten Const intquizzes=5; One  A  - intMain () - { theStudent ada[pupils]= - {Student (quizzes), Student (quizzes), Student (quizzes)}; -  -     inti; +      for(i=0; i<pupils;++i) {="" Set(ada[i],quizzes); =""}=""cout=""><<"\nstudents list\n"; -      for(i=0; i<pupils;++i) {=""cout=""><< Ada[i]. Name () <<Endl; +     } Acout<<"\nresults:"; at      for(i=0;i< pupils;++i) -     { -cout<< endl<<Ada[i]; -cout<<"Average:"<< ada[i].average () <<Endl; -     } -cout<<"done.\n"; in     return 0; - } to  + void Set(Student & SA,intN) - { thecout<<"Please enter the student's name:"; * getline (CIN,SA); $cout<<"Please enter"<< N <<"a score: \ n";Panax Notoginseng      for(intI=0;i< n;i++) -     { theCin>>Sa[i]; +     } A      while(CIN.)Get()!='\ n') the         Continue; +}

Function Description:

    • Question one: Getline (CIN,SA);

Note: There must be no spaces at the time of entry

  • Question two:cin>>sa[i];
  • In the implementation of the SET function, he invokes the first function, but why is the return type a reference, and what is the difference between the two functions?
    1 Double& Student::operator[](inti)2 {3     returnScores[i];4 }5 6 DoubleStudent::operator[](intIConst7 {8     returnScores[i];9}

 

C + + code reuse-student (learning notes)

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.