C + + Primer (Fifth edition) learning notes and exercise Answer Code edition (chapter sixth) functions

Source: Internet
Author: User

Notes are scattered, are not familiar with their own knowledge points.

Exercise answer as for a. CC, the compilation needs to include the Chapter6.h header file. Need to demonstrate a topic directly modified #define num***, such as Run 6.23 titled # define NUM623;

Chapter 6

1.
The mechanism of parameter initialization is the same as the initialization of variables.
When a parameter is a reference type, its corresponding argument is passed by reference or the function is invoked by reference.
2.
Const and actual parameters
void FCN (const int i) {/*FCN can read I, but cannot write value to I */}
void FCN (int i) {/*....*/}//Error, FCN (int) defined repeatedly
A function with the same name is allowed in C + +, but the formal parameter lists of different functions should differ. The top-level const is ignored here, so the two FCN function parameters passed in can be exactly the same.
3.
You cannot pass const objects, literals, or objects that require type conversions to normal reference parameters. Try to use a constant reference rather than a normal reference.
When an array is the most formal parameter, it is not allowed to copy an array and to use an array when it is converted to a pointer. Because the array cannot be copied, we
Array parameters cannot be used in a way that is passed by value. Because arrays are converted to pointers, when an array is passed for a function, the actual
is a pointer to the first element of the array.
References to array parameters:
Func (int (&arr) [10]);
4.
Like vectors, Initializer_list is also a template type, and when you define a Initializer_list object, you must describe the type of elements contained in the list.
Do not return a reference or pointer to a local object:
Once the function is complete, the storage space it occupies is also freed. A function termination means that a reference to a local variable will point to a region of memory that is no longer valid.
5.
The most straightforward way to return an array pointer is to use the type alias
typedef int ARRT[100];
Using ARRT = int[10];
arrt* func (int i);
6.
Overloaded functions should be different on the number of formal parameters or parameter types. Two functions are not allowed except the return type, all other features are the same, or an error.
In the C + + language, type lookups occur before type checking.
Once the desired name is found in the current local scope, the compiler ignores the entity with the same name in the outer scope, and the rest of the work is to check whether the function call is valid.
7.
A local variable cannot be the default argument. In addition, the expression can be used as the default argument as long as the type of the expression can convert the type required by the forming parameter.
Calling a function is generally slower than finding the value of an equivalent expression.
A function call consists of a sequence of functions: Save the Register before the call, and restore it on return; you may need to copy the arguments, and the program will move on to a new location to continue execution.
An inline declaration simply makes a request to the compiler, which the compiler can choose to ignore.
The constexpr function refers to a function that can be used for constant expressions. Define constexpr to comply with Xu several conventions:
The return type of a function and the type of all formal parameters are literal types, and there must be only one return statement in the body of the function.
8.
Assert is a preprocessing macro, which is a preprocessing variable that behaves somewhat like an inline function:
ASSERT (expr);
Evaluates expr first, asserts output information, and terminates execution of the program if the expression is false. If an expression is true, Assert does nothing.
9.
Ndebug preprocessing variables:
The behavior of an assert depends on the state of a preprocessing variable named Ndebug. If Ndebug is defined, assert does nothing. Default does not define
Ndebug, the assert will be executed.
_ _file_ _ string literal that holds the file name
_ _line_ _ The integer literal that holds the current line number
10.
The function pointer points to a function, not an object. It points to a type type, and the function pointer is determined by its return type and formal parameter type, regardless of the function name.
BOOL Lengthcompare (const string&, const string &);
BOOL (*PF) (const string &, const string &); PF points to the function, which is a reference to the two const string.
When we use the function name as a value, the Change function is automatically converted to a pointer.
void Usebright (const string &S1, const string &S2, BOOL PF (const string &, const string &));
Equivalent to: PF is automatically converted as a parameter to a pointer
void Usebright (const string &S1, const string &S2, BOOL (pf*) (const string &, const string &));
Similarly, the simplest way to declare a function that returns a function pointer is to use a type alias.

#include <iostream> #include "Chapter6.h" using namespace Std;int Main () {cout << "5! Is "<<fact (5) <<endl;cout << func () <<endl;cout << abs ( -2.34) <<endl;}
#include <iostream> #include "Chapter6.h" using namespace std;int fact (int val) {if (val = = 0 | | val ==1) return 1;else R Eturn val * fact (VAL-1);} int func () {int n, ret =1;cout<< "Enter a number:" <<endl;cin >> n;while (n > 1) ret *= n--;return ret;}

#include <iostream> #include <vector> #include <cstring> #include <cassert> #include " Chapter6.h "#define Num648#define Ndebug using namespace std;/*6.3*/int fact (int val) {if (val = = 0 | | val ==1) return 1;else Return val * fact (VAL-1);} /*6.4*/int fact2 () {int val;cout << "Enter a number:" <<endl;while (Cin >> val) {if (val = = 0 | | Val < 0) cout<< "Please input a positive number. "<<endl;cout<< val;unsigned Long long exp = 1;exp = Fact (val);cout<<"! is: "; if (exp) cout << exp <<endl;else cout<<" too big. " <<endl;}} /*6.5*/#ifdef num65template <typename t>t abs (T val) {return val > 0 val:-val;} #endif/*6.6*/int Temp (int val1) {static int val2 = 0;val2 + = Val1;return val2;} /*6.7*/int func () {static int flag = 0;return flag++;} /*6.10*/void Swap (int *val1, int *val2) {int temp;temp = *val1;*val1 = *val2;*val2 = temp;} /*6.11*/void Reset (int &val) {val = 0;} /*6.12*/void swap2 (int &val1, int &VAL2) {int temp;temp = Val1;val1 = Val2;val2 = temp;} /*6.17*/bool hasupper (String &s) {for (String::iterator it = S.begin (); It! = S.end (); ++it) {if (Isupper (*it)) return True;else return false;}} void Changtolower (string& s) {for (size_t it = 0; it = s.size ()-1; ++it) {if (Isupper (S[it])) {S[it] = ToLower (S[it]);}} /*6.18*/class Matrix;bool Compare (Matrix &ma1, Matrix &ma2); vector<int>::iterator change_val (int, Vector<int>::iterator);/*6.21*/int contrast (const int VAL1, const int *p) {return val1 > *p? val1: *p;} /*6.22*/void swap3 (int*& val1, int*& val2) {int* temp;temp = Val1;val1 = Val2;val2 = temp;} /*6.23*/void print (const int *p) {if (p) cout<< *p <<endl;} void print (int size, int str[]) {for (size_t it = 0; it!= size; ++it) cout<< str[it] << Endl;} void print (const int* Beg, const int* end) {for (; beg!= end;) cout<< *beg++ <<endl;} void print (int (&arr) [2]) {for (int i =0; i<= 1; ++i) cout<< Arr[i]<<endl;} /*6.27*/#ifdef num627int sum (initializer_list<int> li) {int sum (0); for (Initializer_list<int>::iterator beg = Li.begin (); Beg!= Li.end (); ++beg) sum + = *beg;return sum;} #endif/*6.30*/#ifdef num630bool str_subrange (const string &AMP;STR1, const string &str2) {if (str1.size () = = Str2.size ()) return str1 = = str2;size_t size = str1.size () < Str2.size ()? Str1.size (): Str2.size (); for (size_t i =0; i!= size; ++i) {if (Str1[i]! = Str2[i]) return;} #endif/*6.33*/int &get (vector<int> &ia, int index) {return ia[index];} void print (Vector<int>::iterator Beg, Vector<int>::iterator end) {if (Beg! = end) {cout << *beg << "";p rint (Next (Beg), end);}} /*6.35*/int factorial (int val) {if (Val > 1) return factorial (VAL-1) * Val;return 1;} /*6.36*/string (&func2 (String (&AMP;STR) [)]) [10];/*6.37*/#ifdef num637typedef string Arrt[10];arrt &func3 ( arrt& str); auto Func4 (arrt& str), String (&) [10];string arrs[10];d ecltype (arrs) & Func5 (Arrt& STR); #endif/*6.38*/int odd[] = {1,3,5,7,9};int even[] = {0,2,4,6,8};typedef int arrint[5];arrint& arrptr (int i) {Retu RN (i% 2)? Odd:even; Return reference}/*6.42*/string make_plural (size_t ctr, const string& Word, const string &ending = "S") {return (Ctr > 1) ? Word + Ending:word;} /*6.44*/inline bool Isshorter (const string &AMP;S1, const string &s2) {return s1.size () < S2.size ();} #ifdef NUM646/*6.46*/CONSTEXPR bool IsShorter1 (const string &AMP;S1, const string &s2) {return s1.size () < S2.size ( );} #endif/*6.47*/#ifdef num647void printvector (vector<int>& vec) {#ifdef ndebugcout << "vector size:" < < Vec.size () <<endl; #endifif (!vec.empty ()) {Auto temp = Vec.back (); Vec.pop_back ();p rintvector (VEC); cout < < temp << "";}} #endif/*6.51*/#ifdef num651void f () {cout << "f ()" &LT;&LT;ENDL;} void f (int) {cout << "f (int)" &LT;&LT;ENDL;} void f (int, int) {cout << "f (int, int)" &LT;&LT;ENDL;} void f (double, double = 3.14) {cout &LT;&LT "F (duble, double)" &LT;&LT;ENDL;} #endif/*6.54*/typedef int Func6 (int, int);vector<func6*> vec;/*6.55*/int Add (int a, int b) {return a + B;} int substact (int a, int b) {return a-A;} int multiply (int a, int b) {return a * b;} int divide (int a, int b) {return B!=0? A/b: 0;} the int main () {/*6.1*/#ifdef num61cout<< argument is the initial value of the formal parameter, and the type of the argument must match the corresponding parameter type. "<<endl; #endif/*6.2*/#ifdef num62cout<<" (a) return type mismatch, type int to string, (b) no return type defined for function, can be substituted with void; (c) Absence of a parenthesis; (d) The function body is missing a pair of parentheses. " <<endl; #endif/*6.3*/#ifdef num63cout << "5!:" << fact (5) <<endl; #endif/*6.4*/#ifdef Num64fact2 (); #endif/*6.5*/#ifdef num66cout << "The Absolute of-2.34 is:" << abs ( -2.34) <<endl; #endif/ The life cycle of a *6.6*/#ifdef num66cout<< "parameter is destroyed from the beginning of the function to the termination of the function, and the life cycle of the local variable is terminated from its creation to the function body. Static local variables are initialized until the end of the program is destroyed. "<<endl;for (int val3 = 0; Val3!=10; ++VAL3) cout << "Static variables and local variables are the same as:" << temp (VAL3) <<endl; #endif/*6.7*/#ifdef num67for (int i = 0; i!=4; ++i) cout<< func () <<endl;#endif/*6.8*/#ifdef num68cout<< "See Chapter6.h" <<endl; #endif/*6.9*/#ifdef num69cout<< "See fact.cc factmain.cc "<<endl; #endif/*6.10*/#ifdef num610int val1 = 1, Val2 = 2;swap (&val1, &val2);cout<<" Val1: "<< val1 <<" val2: "<< val2<<endl; #endif/*6.11*/#ifdef num611int val = 23;reset (val); cout << "Val has been reset:" << val <<endl; #endif/*6.12*/#ifdef num612for (int val1 (0), val2 (0); cout<< "Enter numbers: \ n", cin >> val1 >> val2;) {swap2 (Val1, Val2);cout<< "val1:" << VA L1 << "Val2:" << Val2<<endl;} #endif/*6.13*/#ifdef num613cout<< "The first is a value call, the value of the argument is not modified during the call, and the second is called by the address reference, which is bound to the argument during the call. "<<endl; #endif/*6.14*/#ifdef num614cout<<" The reference type in the 6.11 example avoids copying, but cannot use reference parameters when the arguments do not want to be changed. " <<endl; #endif/*6.15*/#ifdef num615cout<< "First, the argument s cannot be changed, but the last value of the occur is calculated by the function; C may be a temporary variable that can be replaced by another value; if the interchange type , S can be changed, occur cannot be changed, = 0, error "<<endl; #endif/*6.16*/#ifdef NUM616COUT&LT;&LT; "Should be set to a const reference, because s does not want to be changed, avoids copying, and uses string constants directly as arguments." <<endl; #endif/*6.17*/#ifdef num617string s = "C + + & Linux", if (Hasupper (s)) cout << "has upper letter." <<endl;elsecout << "No upper letter." <<endl;changtolower (s); cout << "after ToLower:" << s <<endl; #endif/*6.18*/#ifdef num618cout << "See main function declaration;" <<endl; #endif/*6.19*/#ifdef num619cout<< "(a) is illegal, Calc has only one parameter." <<endl;# endif/*6.20*/#ifdef num620cout<< "can generally be const, and if set to a normal reference, it may change the value of the constant in the function." <<endl; #endif/*6.21*/#ifdef num621int val1 (2), Val2 (3); cout << "Return the larger:" << contrast (Val1, &AMP;VAL2) << Endl, #endif/*6.22*/#ifdef num622int val1 (2), Val2 (3); int* P1 = &val1; int* P2 = &val2;swap3 (P1, p2), cout << "val1:" << *p1 << "val2:" << *p2 << Endl; #endi f/*6.23*/#ifdef num623int i =0, j[2] = {0, 1};p rint (&i);p rint (2, j);p Rint (Begin (j), End (j));p Rint (j); #endif/*6.24*/ #ifdef Num624cout<< "No problem, singular if you just want to iterate over an array, you can simply pass it as a pointer or reference." Void print (const int (&ia) [ten]) "<<endl; #endif/*6.25*/# Ifdef num625cout<< "See main-6.25.cc" <<endl; #endif/*6.26*/#ifdef num626cout<< "See main-6.26.cc" < <endl; #endif/*6.27*/#ifdef num627cout << "Sum of 1-5:" << sum ({1,2,3,4,5}) <<endl; #endif/*6.28*/# ifdef num628cout << elem type is const string& <<endl; #endif/*6.29*/#ifdef num629cout << " Because initializer_list elements are always const types and cannot be changed within a function, they should be declared as constant reference types. "<<endl; #endif/*6.30*/#ifdef num630cout<<" See main function declaration outside function; "<<endl; #endif/*6.31*/#ifdef num631cout << "Returns a reference to a local variable that is not valid; If you attempt to assign a value to a return constant reference type, it is not valid. " <<endl; #endif/*6.32*/#ifdef num632cout<< "Legal, function is to assign 0-9 to the IA array" <<endl; #endif/*6.33*/#ifdef   Num633vector<int> VEC (10,0); Initialization is required, otherwise the parameter will be faulted for (int i =0; I! =) ++i get (VEC, i) = I;print (Vec.begin (), Vec.end ()) cout <<endl; #endif/*6.34*/ #ifdef num634cout << "If Val is negative, a stack overflow will occur. "<<endl; #endif/*6.35*/#ifdef num635cout << factorial (5) <<endl;cout << "val--not recursive, error" <<endl; #endif/*6.36*/# Ifdef num636cout<< "See main function outside function declaration, the first kind of declaration clear, modify and read more convenient. "<<endl; #endif/*6.37*/#ifdef num637cout<<" See main function declaration outside function; "<<endl; #endif/*6.38*/#ifdef num638cout << "See main functions outside function declaration;" <<endl; #endif/*6.39*/#ifdef num639cout << "(a) illegal, top-level const, repeating declaration. (b) Illegal, with the same function parameters. (c) Legal. "<<endl; #endif/*6.40*/#ifdef num640cout<<" (b) is illegal, and once a parameter is given a default value, all parameters following it must have a default value. " <<endl; #endif/*6.41*/#ifdef num641cout<< "(a) is illegal and does not give the first parameter a value. (b) Legal. (c) Legal, we are assigned the value of ' * ', but are inconsistent with the intention. "<<endl; #endif/*6.42*/#ifdef num642cout <<" singual: "<< make_plural (1," Success "," es ") <<" "& lt;< make_plural (1, "failure") <<endl;cout << "plural:" << make_plural (2, "Success", "es") << "" << make_plural (2, "failure") <<endl; #endif/*6.43*/#ifdef num643cout << "(a) inline functions are placed in the header file. (b) The function declaration is placed in the header file. "<<endl; #endif/*6.44*/#ifdef NUM644cout << Isshorter ("C + +", "Linux") <<endl; #endif/*6.45*/#ifdef num645cout << "The declaration of an inline function is appropriate for those short code, And the function that is easy to be called frequently. "<<endl; #endif/*6.46*/#ifdef num646cout << isShorter1 (" C + + "," Linux ") <<endl; #endif/*6.47*/#ifdef Num647vector<int> vec{1,2,3,4,5};p rintvector (VEC) cout <<endl; #endif/*6.48*/#ifdef num648string S, Sought ("no"); while (CIN >>s && s! = sought) {}assert (CIN);cout<< "unreasonable, because CIN input always has content, Therefore, the expression in the Assert is always true, and the Assert is not performed. The first step in the <<endl; #endif/*6.49*/#ifdef num649cout << function match is to select the set of overloaded functions that the call corresponds to, and the function in the collection is called the candidate function. The second step examines the actual arguments provided by this invocation, and then selects the functions that can be called by this set of arguments from the candidate functions, which are called viable functions. "<<endl; #endif/*6.50*/#ifdef num650cout <<" (a) 2.56 matches double, but 42 matches int. (b) match void f (int). (c) match void f (int, int). (d) match void F (double, double = 3.14); " <<endl; #endif/*6.51*/#ifdef num651f (2.56), F (0), F (2.56, 3.14), #endif/*6.52*/#ifdef num652cout << "(a) 3, matching by type elevation implementation. (b) 4, a match implemented by an arithmetic type conversion. "<<endl; #endif/*6.53*/#ifdef NUM653COUT << "(a) has no effect, the const is the top-level implementation, and the second sentence implements the function overloading. (b) Unlawful, repeated statements. " <<endl; #endif/*6.54*/#ifdef num654cout << "see the declaration outside the main function. "<<endl; #endif/*6.55*/#ifdef num655vec.push_back (add); Vec.push_back (substact); Vec.push_back (multiply); Vec.push_back (divide); for (Vector<func6*>::iterator it = Vec.begin (); It! = Vec.end (); ++it) cout << (*it) (  << ""; *it parentheses are necessary, otherwise the function returns a pointer of type vector, not a function pointer. cout <<endl; #endifreturn 0;}

Resources:

C + + Primer Chinese version Fifth edition, electronic industry press.
C + + Primer Fourth Edition exercise solution, People's post and telecommunications publishing house.




C + + Primer (Fifth edition) learning notes and exercise Answer Code edition (chapter sixth) functions

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.