"C + + Programming thought" chapter II data Abstraction (original book code + Exercise + answer)

Source: Internet
Author: User
Tags assert

The relevant code such as the following:

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 slice supported by the C compiler. Although on some machines//it may be as large as the largest, this depends on the detailed implementation. The memory that storage points to is allocated}stash;void Initialize (stash* S, int Size) from the heap, and//initialize () completes the necessary settings for the struct Stash. That is, set the internal variable to the appropriate value.

Initially, set the//storage pointer to zero. Setting the size indicator is also zero, indicating that the initial store is not assigned.

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); The fetch () first looks at whether the index is out of bounds, assumes no bounds, returns the desired variable address, and computes the address in the same way as the//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 () takes the stored-order head address that has already been allocated and wants to redistribute as its first parameter (assuming that this is zero, for example, Initialize () has just been tuned. ReAlloc () assigns a new block). The second parameter is the new length of the block, assuming the length is smaller than the original one. This block will not need to be copied. Simply tell the heap manager that the rest of the space is spare.

Suppose the length is larger than the original. There is not enough phase space in the heap, so allocate new blocks and copy the memory. ASSERT () Check to make sure that the operation was successful. (Let's say the heap is exhausted.) malloc (), Calloc (), and realloc () all return zeros.

) */</span>


<span style= "FONT-SIZE:18PX;" >/*test.c*//* If there is a programming tool, it behaves like an array when it is created. But its length can be established at the time of execution. 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 () starting copy byte, which is generated by the following expression: & (S->storage[s->next * s->size]) it indicates the end of the next available unit starting from the storage block. This number is actually the count of the unit number plus one that has been used, and it must multiply the number of bytes owned by each cell to produce an offset in bytes.

This does not produce an address. Instead, it produces bytes at this address. In order to generate an address, the address operator & must be used. The second and third parameters of memcpy () are the start address of the copied variable and the number of bytes to be copied. n e x t counter plus one. and returns the index of the stored value.

Such The program ape 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 (), the ability to assign void * to any other pointer. 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 on some machines//it may be larger than the largest, which relies on a detailed implementation. The memory that storage points to allocates void initialize (int Size) from the heap, and//initialize () finishes the necessary setting for the struct stash, which is to set the internal variable to the appropriate value. Initially, set the//storage pointer to zero. Setting the size indicator is also zero, indicating that the initial store is not assigned.           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); The fetch () first looks at whether the index is out of bounds, assumes no bounds, returns the desired variable address, and computes the address in the same way as the//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 already been allocated and wants to redistribute as its first parameter (assuming that this is zero, for example, Initialize () has just been tuned. ReAlloc () assigns a new block). The second parameter is the new length of the block, assuming the length is smaller than the original one. This block will not need to be copied, simply tell the heap manager that the rest of the space is spare. Assuming the length is larger than the original, there is not enough space in the heap. So you want to allocate new blocks and copy the memory. ASSERT () Check to make sure that the operation was successful.

(Let's say the heap is exhausted.) malloc (), Calloc (), and realloc () all return zeros.

) */};</span>



<span style= "FONT-SIZE:18PX;" >/*test.cpp*//* If there is a programming tool. It behaves like an array when it is created, but its length can be established at execution 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, and the first parameter is the destination address of the memcpy () to start copying bytes, Generated by the following expression: & (S->storage[s->next * s->size]) it indicates the end of the next available unit starting from the storage block. This number is actually the count of the unit number plus one that has been used, and it must multiply the number of bytes owned by each cell to produce an offset in bytes. This does not produce an address, but rather produces the byte at that address in order to generate the address. You 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 program ape is able to 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 on some machines//it may be larger than the largest, which relies on a detailed implementation. The memory that storage points to is allocated from the heap}stash;void Initialize (stash* S, int Size), and//initialize () completes the necessary setting for 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 space available. If//The fruit is not, it expands the storage space with the inflate () function described later.

void* Fetch (stash* S, int index); The fetch () first looks at whether the index is out of bounds, assumes no bounds, returns the desired variable address, and computes the address in the same way as the//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 () takes the stored-order head address that has been allocated and wants to be redistributed as its first parameter (assuming that the number is zero. For example, when initialize () has just been called, realloc () allocates a new block). The second parameter is the new length of the block. Assuming the length is smaller than the original, this block will not need to be copied, simply tell the heap manager that the rest of the space is spare. Assuming the length is larger than the original, there is not enough space in the heap. So you want to allocate new blocks and copy the memory. ASSERT () Check to make sure that the operation was successful. (Let's say 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 on some machines//it may be as large as the largest. This depends on the detailed implementation. The memory that storage points to allocates void initialize (int Size) from the heap, and//initialize () finishes the necessary setting 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. Indicates that the initial storage was 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 see if the index is out of bounds. Assume no bounds. Returns the desired variable address, calculated using the same method as the//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 a stored-order head address that has already been allocated and wants to be redistributed as its first parameter (assuming that the parameter is zero, such as when Initialize () has just been called, realloc () allocates a new block). The second parameter is the new length of the block, assuming the length is smaller than the original one. This block will not need to be copied. Simply tell the heap manager that the rest of the space is spare. Assuming 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. (Assuming that 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 mysterious because it is not a data member of structprintf (" 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 structure length in C + + is the same as the length of the equivalent version number in C.

C + + Try not to add whatever costs */return 0;} </span>



5.

<span style= "FONT-SIZE:18PX;" > #ifndef nested_h_#define nested_h_struct stack//This nested struct is called link. It contains a pointer to the next link in the table and a pointer to the data stored in the link. Assume that the next pointer is zero. 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 the number of parameters and assigns the parameters to its members {data = Data;next = Next;} The void Stack::initialize ()//stack::initialize () function resets the head to zero. Makes this object aware that it has an empty table {head = 0;} void stack::p ush (void* data)//stack::p Ush () takes 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. Use Free () to release each link's data and link itself {link* cursor = Head;while (head) {cursor = Cursor->next;free (head->data); ); 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;//assumes that there is no scope decomposition in s::f (). The compiler chooses F () and A's member version number by default int a;void f () {}struct s{int 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. The definition is then created for this 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 call.

#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 a sample (nested structure) of the declared structure in a 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 the parameter and output {cout<< "the school's address:" << Address<<endl;} void family::families (int number)//take the parameter and output {cout<< "the family ' s people numbers:" <<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 some structures. They have only data members. There are also data members and function members. It then creates a struct that has no members at all. Prints out the length 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));//each 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 mysterious, because it is no data member of Structreturn 0;}


5) C + + for enumerations, unions, and structs themselves to create the equivalent of a TypeDef, 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 only for reference, if there are errors I hope you can point out, thank you.


"C + + Programming thought" chapter II data Abstraction (original book code + Exercise + answer)

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.