The relevant code is as follows:
1.
<span style= "FONT-SIZE:18PX;" >/* declaration and definition difference */#include <iostream>using namespace Std;extern int i;//declaration extern float F (float);//Declaration float b;//Definition + Declare float f (float a)//definition {return a + 1.0;} int i;//definition int h (int x)//definition + Declaration {return x + 1;} int main () {b = 1.0;i = 2;cout<<f (b) <<endl;cout<
2.<span style= "FONT-SIZE:18PX;" >/*test.h*/#include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h>/ * A Pocket C library c */typedef struct stashtag{int size; Size of each spaceint quantity; Number of storage spacesint next; Next empty spaceunsigned char* storage;//storage pointer is a unsigned char*. This is the smallest memory chip supported by the C compiler, although it may be larger than the largest in some machines//, depending on the implementation. The memory that storage points to is allocated from the heap}stash;void Initialize (stash* S, int Size), and//initialize () completes the necessary settings for the struct Stash, which is to set the internal variable to the appropriate value. Initially, the set//storage pointer is zero, and the size indicator is set to zero, indicating that the initial store is not allocated. void Cleanup (stash* S); Clear int Add (stash* S, void* Element); The Add () function inserts an element on the next available seat in the stash. First, it checks to see if there is free space, such as//fruit, which expands the storage space with the inflate () function described later. void* Fetch (stash* S, int index); Fetch () First look at whether the index is out of bounds, if not out of bounds, return the desired variable address, the address is computed using the same method as in//add () int count (stash* S);Returns the stored space size void inflate (stash* S, int increase), and the/*inflate () function uses realloc () to get a larger block of space for Stash. ReAlloc () assigns a stored-order head address that is already assigned and wants to be redistributed as its first parameter (if this parameter is zero, for example, Initialize () is just being called, realloc () allocates a new block). The second parameter is the new length of the block, and if the length is smaller than the original, the block will not need to be copied, simply tell the heap manager that the rest of the space is idle. If the length is larger than the original, there is not enough phase space in the heap, so allocate a new block and copy the memory. ASSERT () Check to make sure that the operation was successful. (If the heap is exhausted, malloc (), Calloc (), and realloc () all return zeros. ) */</span>
<span style= "FONT-SIZE:18PX;" >/*test.c*//* assumes that there is a programming tool that behaves like an array when it is created, but its length can be established at run time. I call it stash*/#include "test.h" void Initialize (stash* S, int Size) {s->size = size; s->quantity = 0; s->storage = 0; S->next = 0; }void Cleanup (stash* S) {if (s->storage) {puts ("freeing storage"); free (s->storage);}} int Add (stash* S, void* Element) {if (S->next >= s->quantity) {inflate (s,100);} memcpy (& (S->storage[s->next * s->size]), element,s->size);/* We must use the standard C library function memcpy () to copy this variable one byte at a byte, The first parameter is the destination address of the memcpy () to begin copying bytes, produced by the following expression: & (S->storage[s->next * s->size]) it indicates the end of the next available cell starting at the storage block. This number is actually a count of the number of units that have been used, plus one, which must multiply the number of bytes owned by each cell, resulting in a byte-based offset. This does not produce an address, but rather produces a byte at this address, in order to generate the address, must use the address operator &. The second and third parameters of memcpy () are the start address of the copied variable and the number of bytes to be copied. The n e x T counter adds one and returns the index of the stored value. In this way, the programmer can use it to get this element when it calls fetch () later. */s->next ++;return (s->next-1);} void* Fetch (stash* S, int index) {if (index >= s->next | | Index < 0) {return 0;} Return & (S->storage[index * s->size]);}int count (stash* S) {return s->next;} void Inflate (stash* S, int increase) {void* v = realloc (S->storage, (s->quantity + Increase) *s->size); assert (v); S->storage = v;//in the C Library of Inflate (), you can assign void * to any other pointers, such as S->storage = V, and the compiler can pass. S->quantity + = increase;} </span>
<span style= "FONT-SIZE:18PX;" >/*main.c*/#include "test.h" #define BUFSIZE 80int Main () {Stash intstash,stringstash;int i; file* File;char buf[bufsize];char* cp;initialize (&intstash,sizeof (int)); for (i = 0;i < 100;++i) {Add (& Intstash,&i);} Initialize (&stringstash,sizeof (char) *bufsize), File = fopen ("Main.c", "R"), assert (file), while (Fgets (BUF, BUFSIZE, file) {Add (&stringstash, buf);} fclose (file); for (i = 0;i < count (&intstash); ++i) {printf ("Fetch (&intstash,%d) =%d\n", I, * (int*) Fetch (& intstash,i));} i = 0;while ((CP = FETCH (&stringstash,i++))! = 0) {printf ("Fetch (&stringstash,%d) =%s", I-1,CP);} Putchar (' \ n '); Cleanup (&intstash); Cleanup (&stringstash); return 0;} </span>
3.<span style= "FONT-SIZE:18PX;" > #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h>//c++struct Stash{int size; Size of each spaceint quantity; Number of storage spacesint next; Next empty spaceunsigned char* storage; The storage pointer is a unsigned char*. This is the smallest memory chip supported by the C compiler, although it may be larger than the largest in some machines//, depending on the implementation. The memory that storage points to allocates void initialize (int Size) from the heap, and//initialize () completes the necessary settings for the struct stash, which is to set the internal variable to the appropriate value. Initially, the set//storage pointer is zero, and the size indicator is set to zero, indicating that the initial store is not allocated. void Cleanup (); Clear int Add (void* element); The Add () function inserts an element on the next available seat in the stash. First, it checks to see if there is free space, such as//fruit, which expands the storage space with the inflate () function described later. void* Fetch (int index); Fetch () First look at whether the index is out of bounds, if not out of bounds, return the desired variable address, the address is computed using the same method as in//add () int count (); Returns the stored space size void inflate (int increase), and the/*inflate () function uses realloc () to get a larger block of space for stash. ReAlloc () takes the stored-order head address that has been allocated and wants to redistribute as its firstParameter (if this parameter is zero, for example, Initialize () has just been called, realloc () allocates a new block). The second parameter is the new length of the block, and if the length is smaller than the original, the block will not need to be copied, simply tell the heap manager that the rest of the space is idle. If the length is larger than the original, there is not enough phase space in the heap, so allocate a new block and copy the memory. ASSERT () Check to make sure that the operation was successful. (If the heap is exhausted, malloc (), Calloc (), and realloc () all return zeros. ) */};</span>
<span style= "FONT-SIZE:18PX;" >/*test.cpp*//* assumes that there is a programming tool that behaves like an array when it is created, but its length can be established at run time. I call it stash*/#include "test.h" void stash::initialize (int Size) {size = size; quantity = 0;storage = 0; next = 0; }void Stash::cleanup () {if (storage) {puts ("freeing storage"); free (storage);}} int Stash::add (void* element) {if (next >= quantity) {inflate (100);} memcpy (& (Storage[next * size]), element,size);/* We must use the standard C library function memcpy () to copy the variable one byte at a byte, the first parameter is memcpy () the destination address of the copy byte, Generated by the following expression: & (S->storage[s->next * s->size]) it indicates the end of the next available cell starting at the storage block. This number is actually a count of the number of units that have been used, plus one, which must multiply the number of bytes owned by each cell, resulting in a byte-based offset. This does not produce an address, but rather produces a byte at this address, in order to generate the address, must use the address operator &. The second and third parameters of memcpy () are the start address of the copied variable and the number of bytes to be copied. The n e x T counter adds one and returns the index of the stored value. In this way, the programmer can use it to get this element when it calls fetch () later. */next ++;return (next-1);} void* stash::fetch (int index) {if (index >= Next | | Index < 0) {return 0;} Return & (Storage[index * size]);} int Stash::count () {return next;} void stash::inflate (int increase) {void* v = realloc (storage, quantity + IncreaSE) *size); assert (v); storage = (unsigned char*) v;quantity + = increase;} </span>
<span style= "FONT-SIZE:18PX;" > #include "test.h" #define BUFSIZE 80int Main () {stash intstash,stringstash;int i; file* File;char buf[bufsize];char* cp;intstash.initialize (sizeof (int)); for (i = 0;i < 100;++i) {Intstash.add (&i) ;} Stringstash.initialize (sizeof (char) *bufsize), File = fopen ("Main.cpp", "R"), assert (file), while (Fgets (buf, BUFSIZE, File) {Stringstash.add (BUF);} fclose (file); for (i = 0;i < Intstash.count (); ++i) {printf ("intstash.fetch (%d) =%d\n", i,* (int*) Intstash.fetch (i));} i = 0;while ((cp = (char*) stringstash.fetch (i++))! = 0) { printf ("stringstash.fetch (%d) =%s", I-1,CP);} Putchar (' \ n '); Intstash.cleanup (); Stringstash.cleanup (); return 0;} </span>
4.<span style= "FONT-SIZE:18PX;" >/*1.h C */typedef struct stashtag{int size; Size of each spaceint quantity; Number of storage spacesint next; Next empty spaceunsigned char* storage;//storage pointer is a unsigned char*. This is the smallest memory chip supported by the C compiler, although it may be larger than the largest in some machines//, depending on the implementation. The memory that storage points to is allocated from the heap}stash;void Initialize (stash* S, int Size), and//initialize () completes the necessary settings for the struct Stash, which is to set the internal variable to the appropriate value. Initially, the set//storage pointer is zero, and the size indicator is set to zero, indicating that the initial store is not allocated. void Cleanup (stash* S); Clear int Add (stash* S, void* Element); The Add () function inserts an element on the next available seat in the stash. First, it checks to see if there is free space, such as//fruit, which expands the storage space with the inflate () function described later. void* Fetch (stash* S, int index); Fetch () First look at whether the index is out of bounds, if not out of bounds, return the desired variable address, the address is computed using the same method as in//add () int count (stash* S); Returns the stored space size void inflate (stash* S, int increase), and the/*inflate () function uses realloc () to get a larger block of space for Stash. ReAlloc () The storage that has been allocated and wants to be redistributedSingle head address as its first parameter (if this parameter is zero, for example initialize () is just being called, realloc () allocates a new block). The second parameter is the new length of the block, and if the length is smaller than the original, the block will not need to be copied, simply tell the heap manager that the rest of the space is idle. If the length is larger than the original, there is not enough phase space in the heap, so allocate a new block and copy the memory. ASSERT () Check to make sure that the operation was successful. (If the heap is exhausted, malloc (), Calloc (), and realloc () all return zeros. ) */</span>
<span style= "FONT-SIZE:18PX;" >//c++2.hstruct stash{int size; Size of each spaceint quantity; Number of storage spacesint next; Next empty spaceunsigned char* storage; The storage pointer is a unsigned char*. This is the smallest memory chip supported by the C compiler, although it may be larger than the largest in some machines//, depending on the implementation. The memory that storage points to allocates void initialize (int Size) from the heap, and//initialize () completes the necessary settings for the struct stash, which is to set the internal variable to the appropriate value. Initially, the set//storage pointer is zero, and the size indicator is set to zero, indicating that the initial store is not allocated. void Cleanup (); Clear int Add (void* element); The Add () function inserts an element on the next available seat in the stash. First, it checks to see if there is free space, such as//fruit, which expands the storage space with the inflate () function described later. void* Fetch (int index); Fetch () First look at whether the index is out of bounds, if not out of bounds, return the desired variable address, the address is computed using the same method as in//add () int count (); Returns the stored space size void inflate (int increase), and the/*inflate () function uses realloc () to get a larger block of space for stash. ReAlloc () assigns a stored-order head address that is already assigned and wants to be redistributed as its first parameter (if this parameter is zero, for example, Initialize () is just being called, realloc () allocates a new block). The second parameter is the new length of this block, if the length is smaller than the original, this block will not need to be copied, simply tell the heap pipeThe remaining space of the manager is free. If the length is larger than the original, there is not enough phase space in the heap, so allocate a new block and copy the memory. ASSERT () Check to make sure that the operation was successful. (If the heap is exhausted, malloc (), Calloc (), and realloc () all return zeros. ) */};</span>
<span style= "FONT-SIZE:18PX;" > #include "1.h" #include "2.h" #include <stdio.h>struct a{int i[100];}; struct b{void f ();}; void B::f () {}int main () {printf ("sizeof struct a =%d bytes\n", sizeof (a));//each int accounts for two bytes of printf ("sizeof struct B =%d bytes\ n ", sizeof (b));//struct B is singular because it is structprintf without data members (" sizeof Stash in C =%d bytes\n ", sizeof (Stash));p rintf (" sizeof Stash in C + + =%d bytes\n ", sizeof (stash));/* The last two sizeof statements indicate that the length of the structure in C + + is the same as the equivalent version in C. C + + try not to increase any cost */return 0;} </span>
5.
<span style= "FONT-SIZE:18PX;" > #ifndef nested_h_#define nested_h_struct stack//This nested struct is called link, which includes a pointer to the next link in the table and a pointer to the data stored in the link, if Next The pointer is zero, which means the end of the table. {struct link{void* data;link* next;void Initialize (void* data, link* next);} *head;void Initialize (), void push (void* data), void* Peek (), void* pop (), void Cleanup (),//cleanup remove each stack element, and release the Data pointer};# Endif</span>
<span style= "FONT-SIZE:18PX;" > #include "nested.h" #include <stdlib.h> #include <assert.h>void stack::link::initialize (void* Data, link* Next)//simply use the range decomposition operator two times to indicate the name of the nested struct. The Stack::link::initialize () function takes arguments and assigns parameters to its members {data = Data;next = Next;} The void Stack::initialize ()//stack::initialize () function resets the head to zero so that the object knows it has an empty table {head = 0;} void stack::p ush (void* data)//stack::p Ush () takes a parameter, which is a pointer to a piece of data that you want to save with this stack, and put//this pointer on the top of the stack {link* NewLink = (link*) malloc (sizeof); assert (NewLink); Newlink->initialize (Data, head); head = NewLink;} void* stack::p eek ()//Return the value of head {return head->data;} void* stack::p op ()//stack::p op () takes out the data pointer currently at the top of the stack, then moves the head pointer down, deleting the stack's old stack top element {if (head = = 0) {return 0;} void* result = head->data;link* Oldhead = Head;head = Head->next;free (oldhead); return result;} void Stack::cleanup ()//stack::cleanup () creates a cursor that moves across the stack, releasing each link's data and link itself with free () {link* cursor = Head;while (head) {cursor = Cursor->next;free (head->data); free (head); head = cursor;}} </spAn>
<span style= "FONT-SIZE:18PX;" > #include "nested.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include < Assert.h> #define BUFSIZE 100int Main (int argc, char** argv) {stack textlines; file* file;char* S;char buf[bufsize];assert (argc = 2); textlines.initialize (); file = fopen (Argv[1], "R"); assert (file); while (Fgets (buf, BUFSIZE, file)) {char* string = (char*) malloc (strlen (BUF) +1); assert (string); strcpy (string, buf); Textlines.push (string);} while ((s = (char*) textlines.pop ())! = 0) {printf ("%s", s); free (s);} Textlines.cleanup (); return 0;} </span>
6.
<span style= "FONT-SIZE:18PX;" > #include <iostream>using namespace std;//If there is no scope decomposition in s::f (),//The compiler chooses F () and A's member version by default int a;void f () {}struct s{in T a;void f ();}; void S::f () {:: F ();:: a++; a--;} int main () {return 0;} </span>
1) Create a struct declaration that has a single member function and then creates a definition for the member function. Create An object of this new data type, and then call this member function. #include <iostream>using namespace std;struct student{void play ();}; void Student::p lay () {cout<< "funny!" <<endl;} int main () {Student s;s.play (); return 0;}
2) write and compile a piece of code that completes the data member selection and function invocation.#include <iostream> #include <string>using namespace std;struct student{string address;void Play (string address);}; void Student::p lay (String address) {cout<<address<< "" << "is funny!" <<endl;} int main () {Student s;s.play ("Xi ' an"); return 0;}
3) Write an example of a declared structure in another structure (nested structure). and explains how to define the members of this structure.#include <iostream> #include <string>using namespace std; #ifndef test_h_#define tset_h_struct family{ struct school{string address;void Schools (string address);} *addr;int number;void Families (int number);}; #endif
#include "test.h" void Family::school::schools (String address)//take parameters and output {cout<< "the school's address:" << Address<<endl;} void family::families (int number)//takes arguments and outputs {cout<< "The family's people number:" <<NUMBER<<ENDL;}
#include "test.h" int main () {family F; f.families (5); return 0;}
4) How big is the structure? Write code that can print the length of each structure. Create structures that have only data members and others that have data members and function members. It then creates a struct that has no members at all. Prints out the lengths of all these structures. Explain the results of structures without members at all.#include <stdio.h>struct a{char a;int b;}; struct b{void f ();d ouble D;}; struct C{};void b::f () {}int main () {printf ("sizeof struct a =%d bytes\n", sizeof (a));//int is four bytes, Char takes one byte, But if the multiples of four are eight printf ("sizeof struct B =%d bytes\n", sizeof (b));//Each Double is eight bytes and the function byte number is eight printf ("sizeof struct C =%d bytes\n" , sizeof (c));//struct C is singular, because it is not a data member of Structreturn 0;}
5) C + + is the equivalent of automatically creating a typedef for enumerations, unions, and structs, as seen in this chapter. Write a small program that can illustrate this point.#include <iostream> #include <string>using namespace std;typedef struct {int age;string address;} Student;typedef union{int a;double D;} Number;typedef Enum{white,black,blue,green}colour;int Main () {Student s;s.address = "Xi ' an"; s.age = 18;cout<< " Student's address: "<<s.address<<endl;cout<<" Student ' s Age: "<<s.age<<endl;number N; N.A = 5;cout<< "People number:" <<n.a<<endl;colour c = white;cout<< "Number of enum:" <<c <<endl;return 0;}
for the above answer is for reference only, if have the mistake to want everybody to point out, thank everybody.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"C + + Programming thought" chapter II data Abstraction (exercise + answer)