C++Primer Fifth Edition Chapter 7 Exercise Answers (1-10)

Keywords: C

1: Knowledge Point 1: Method of class Definition: Use and Difference of Strct and class.

Knowledge Point 2: Initialization Method of Members in Class: Initialization List of Members. The compiler calls the constructor to initialize the members and can be overloaded.


First, an example is given to facilitate understanding.

#include <iostream>
#include<string>
#include<vector>
using namespace std;
/*
C++ The struct keyword of C language is retained and expanded. In C language, struct can only contain member variables, not member functions.
In C++, struct is similar to class, which can contain both member variables and member functions.

C++The struct and class are basically generic, with only a few details different:
1:When using class, members in the class default to private attributes; when using struct, members in the structure default to public attributes. (Essential difference)
2:class Inheritance defaults to private inheritance, while struct inheritance defaults to public inheritance (the chapter "C++ Inheritance and Derivation" will explain inheritance).
3:class Templates can be used, but struct cannot.
*/

//class Definition
class Student
{
	Student(string name, int age, int score);//Constructor

	string m_name;
	int m_age;
	int m_score;//Define three variables

	void showname()//Define a function
	{
		cout<<m_name<<"Age is:"<<m_age<<",The score is:"<<m_score<<endl;
	}//For functions defined within a class, the compiler takes precedence over inline functions
public:
private:
protected://Three forms
};
Student::Student(string name, int age, int score):m_name(name), m_age(age), m_score(score){ }
//Members initialize the list, assign name to m_name, and change variables within the class


//Using strcut to define classes
struct Students
{
	Students(string name, int age, int score);//Constructor
	
	string m_name;
	int m_age;
	int m_score;//Define three variables, default public

	void shownames()//Define a function
	{
		cout<<m_name<<"Age is:"<<m_age<<",The score is:"<<m_score<<endl;
	}//Both intra-class and extra-class definitions are in the same file, and can also be defined in. h file.
};
Students::Students(string name, int age, int score):m_name(name), m_age(age), m_score(score){ }
//List initialization to override class internal variables

/*
summary
1: struct As the implementation of data structure, its default data access control is public, while class is the implementation of object, its default member variable access control is private.
2: When you think you're going to do something more like a data structure, use struct. If you're going to do something more like an object, use class. 
3: However, for access control, it should be clearly stated in the program, rather than relying on default, which is a good habit and makes your code more readable. 
*/

int main(int argc, char** argv)
{
	Student stu1("Xiao Ming", 18, 3);//Error reporting: Although declared, it is not accessible. Members are not restricted to public. By default, they are private and are not accessible externally.
	Students stu2("Xiao Ming", 18, 3);//normal
	stu2.shownames();
	return 0;
}


Answer to this question:

#include <iostream>
#include<string>
#include<vector>
using namespace std;
struct Sales_data {
	Sales_data();
	string bookNo;
	unsigned units_sold ;
	double revenue ;//Variable members within a class are not allowed to initialize at definition time. Constructors must be used
};
Sales_data::Sales_data()
{
	units_sold = 0;
	revenue = 0.0;
}

int main(int argc, char **argv)
{
	Sales_data total;//This section is the same as Chapter I, page 21.
	if (cin >> total.bookNo >> total.units_sold >> total.revenue) {
		Sales_data trans;
		while (cin >> trans.bookNo >> trans.units_sold >> trans.revenue) {
			if (total.bookNo == trans.bookNo) {
				total.units_sold += trans.units_sold;
				total.revenue += trans.revenue;//Modifications in the Use of Question 3
			}
			else {
				cout << total.bookNo << " " << total.units_sold << " "
					<< total.revenue << endl;
				total = trans;
			}
		}
		cout << total.bookNo << " " << total.units_sold << " " << total.revenue
			<< endl;
	}
	else {
		std::cerr << "No data?!" << std::endl;
		return -1;
	}
	return 0;
}

2: Knowledge Point 1: Declaring Classes in. h Document is Better

Knowledge Point 2: This refers to the "this" object, which is a constant pointer.

KNOWLEDGE POINT 3: Const immediately after the parameter list means that this is a constant pointer - with respect to const member function, it means that the constant member function can not change the memory of the object that calls it, that is to say, the function can only be accessed and can not be modified.


This section has introduced the information about combine and isbn, which can be added directly.


3: Change the += operation in question 1 to use the combine function.


4. 5: Use class to implement this class

#include <iostream>
#include<string>
#include<vector>
using namespace std;
class Person
{
public://Declare as public
	Person(string Client_name, string Client_address);//Constructor
	Person();//Overload of constructors

	string name;
	string address;//Internal variables

	void Show_info()
	{
		cout<<name<<"'s"<<" address is "<<address<<endl;
	}//Intra-class Definition Function

	string& const getname()
	{
		return name;
	}
	string& const getaddress()
	{
		return address;
	}//Function that returns the name and address, accessible only, not modifiable
};
Person::Person(string Client_name, string Client_address):name(Client_name),address(Client_address){};//Constructor defines internal variables
//Here we define this class in a file. If the class is large, it should be placed in. h file.
int main(int argc, char **argv)
{
	Person Client1("Mr.right","your heart");//instantiation
	Client1.Show_info();//Call the display information function in it
	return 0;
}

It's better to const, which ensures that the function can only access internal variables and not write internal variables.


6. 7: Knowledge Point 1: Although class-related functions can be defined and declared separately, they need to be placed in the same file as the class, so that only one file can be introduced when using the interface.


Add the three functions in the book.

All three operations can be replaced.


8: Knowledge Points: The difference between ordinary and constant citations is whether you want to change it or not.~


9: Knowledge Points: When writing a header file, whether or not it is included in any other header file, a protector should be set to prevent duplicate inclusion.

The following code should be added to the header file:

#ifndef Cccc//When the header file is included for the first time,  ifndef is judged to be true, and the preprocessor processes the following content until  endif, when the preprocessing variable Cccc is defined
#define Cccc//When the header file is included for the second time,  ifndef is judged to be false, and the preprocessor will ignore the following content. Preprocessing variables are generally defined as uppercase header files.
/*
....
*/
#endif// Just add it up, ignoring the scoping rules in C++.


A slight modification will do:

istream& read(istream& is, Person& person)
{
    is >> person.name >> person.address;
    if (!is) person = Person();
    return is;//Return the input stream
}//Accept a reference of IO type as its parameter. IO class belongs to a type that cannot be copied and can only be passed by reference.

ostream& print(ostream& os, const Person& person)
{
    os << person.name << " " << person.address;
    return os;
}



10: It is obvious that the function of conditional sentences is to judge the object of two reading operations at the same time.



Posted by Fjerpje on Sat, 30 Mar 2019 18:15:30 -0700