Summary of C++ knowledge points and exercises

1. Introduction to C++ and basic data types

1. In C++, a function must be declared before it can be used (called).
2. A C++ function declaration always consists of a function prototype.
3. When the parameter is declared, its type should be pointed out.
4. The parameters in the function definition are called formal parameters, or formal parameters for short.
5. The value actually passed when calling the function is called the actual parameter, referred to as the actual parameter.
6. On most computers, short int means 2 bytes long. short can only modify int, and short int can be omitted as short.
7. long can only modify int and double. When it is modified as long int (can be omitted as long), it generally represents 4 bytes; when it is modified long double, it generally represents 10 bytes.
8. unsigned and signed can only modify char and int. In general, the default char and int are signed. The real numbers float and double are always signed and cannot be modified with unsigned.
9. Use typeof (data type) to determine the byte length of a certain data type.
10. Rules for naming variable names:
(1) It cannot be a C++ keyword.
(2) The first character must be a letter or an underscore.
(3) Do not exceed 31 characters.
(4) There can be no spaces in between.
(5) Cannot contain special symbols such as " ; , " ' + - ". In addition to 26 English uppercase and lowercase letters and numbers, only the underscore "_" can be used in variable names. (6) Variable names do
not Same as library function names, class names, and object names in C++.

11. Octal starts with 0 and hex starts with 0x.
12. Decimal numbers have positive and negative points, and octal and hexadecimal numbers can only represent unsigned integers.
13. Exponential form: E or e must be preceded by a number, and the exponent behind E must be an integer.
14. A character is a single character enclosed in single quotes. ' \ddd ' means 1~3 octal numbers, ' \xhh ' means 1~2 hexadecimal numbers.
Example: There are 18 characters in "\x07operating\tsystem\n".
15. In C++, strings always end with '\0'.
16. "0" is not the same as '0'.
17.printf("%-5.3s", "Hello"); The negative sign means left alignment, 5 means the format width, and 3 means to intercept 3 characters in the string.

2. Expressions and Grammar

1. Operator priority: Arithmetic operator > Relational operator > Logical operator > Assignment operator
2. / For integer numbers, it is rounding, and for floating-point numbers, it is division in the usual sense.
3.% can only operate on integer numbers, which means taking the remainder.
4. Arithmetic type conversion is always in the direction of stronger ability to express data, and the conversion is always carried out operator by operator.
5. The type conversion performed automatically during data operation is called implicit type conversion.
6. Mandatory conversion is also known as display conversion, and its syntax is to add a type name with brackets before a value or variable. A type name can also be followed by a parenthesized value or expression. If the type name is modified with a type, the type name must be enclosed in parentheses.
7. Conditional operator (conditional expression)? (expression if condition is true): (expression if condition is false). Conditional operators can be nested.
8.if ( !n ) is equivalent to if ( n == 0 ) and if ( n ) is equivalent to if ( n != 0 )
9. In the do-while loop, the semicolon after the while (continuation condition) is not required forget.
10. The three expressions of the for statement can be omitted, and expressions 1, 2, and 3 can be any expressions.
11. The expression in parentheses behind the switch can only be an expression of integer, character or enumeration type. The type of the constant expression following the case must match it.
12. Because the case statement acts as a statement label, case and default do not change the control flow. Case is often used in conjunction with the break statement to ensure the correct implementation of multi-way branches. The last branch can omit the break statement.
Each case (including default) can appear in any order. In the case that each case branch has a break, the case order does not affect the execution result.
13. The default statement is optional. When default does not appear, when the value of the expression is not equal to the value of all constant expressions, the switch statement is skipped.
14. Switch statements can be nested.
15. The difference between the continue statement and the break statement is: the continue statement only ends the current loop, rather than terminating the execution of the entire loop; while the break statement terminates the entire loop without conditional judgment.

3. Function

1. C++ does not allow function definitions to be nested, that is, it is illegal to define another function in a function definition.
2. A program divides the memory block assigned to it by the operating system into four areas: code area, global data area, heap area, and stack area.
3. When the function ends, the static local variable will not disappear, nor will it reallocate space every time the function is called. It always resides in the global data area until the end of the program execution. The initialization of static local variables is similar to that of global variables. If they are not explicitly initialized, C++ will automatically initialize them to 0.
4. Inline functions are also called inline functions, which mainly solve the operating efficiency of the program.
5. The overloaded functions differ at least in the number of parameters, parameter types or parameter order.
6. The type defined by typedef can only be made the same as an existing type, but cannot create a new type, so the type name defined by typedef cannot be used to distinguish the parameters in the overloaded function declaration.
7. Default parameters are provided in the function declaration. When there are declarations and definitions, default parameters are not allowed in the definition. Default parameters can only appear in a function definition if the function is only defined.
8. The default value can be a global variable, a global constant, or even a function. But the default value cannot be a local variable, because the function call of the default parameter is determined at compile time, and the location and value of the local variable cannot be determined at compile time.
9. The inline function is implemented to improve programming efficiency, and it overcomes the disadvantages caused by the #define macro definition.
10. The goto and switch statements should not cause the control to jump from the scope of a declaration to the scope of the declaration, because this kind of jump jumps over the declaration statement of the variable, so that the variable cannot be initialized.
11. Global variables, static global variables, and static local variables all have a static lifetime. Variables with file scope have a static lifetime. Variables with a static lifetime are automatically initialized to 0 if they are not explicitly initialized.
12. Variables declared inside a function or variables declared in a block have a local lifetime. A variable with local scope has a local lifetime if it is a local variable, and a static lifetime if it is a static local variable. Variables with local lifetime reside in the stack area of ​​memory. Variables with local lifetime have uninitialized contents whose contents are unknown.
14. Three types of compilation preprocessing instructions: #include, #define, #if.
#include Include directive: Let the preprocessor embed a source file at this point in the current file.
#define macro definition directive: Create constants, define macros with parameters, and another effective use is in conditional compilation directives.
15. Conditional compilation instructions are: #if, #else, #elif, #endif, #ifdef, #ifndef, #undef.
An efficient use of conditional compilation is when coordinating multiple header files. A symbol can be undefined using #undef, which turns symbols on and off as needed.

4. Arrays and pointers

1. The number of values ​​in the initialized array cannot be more than the number of elements in the array, and the value of the initialized array cannot be omitted by skipping commas.
2. The number of initialization values ​​can be less than the number of array elements. When the number of initialization values ​​is less than the number of array elements, the previous ones initialize the corresponding values ​​in sequence, and the latter ones are initialized to 0.
3. For the initialization of the string, pay attention to the size of the space actually allocated by the array, which is the number of strings plus the '\0' terminator at the end.
4. The size of the array is n, and the length of the string is n-1.
5. When defining, it is also possible to assign initial values ​​to some elements and omit the size of the first dimension, but the initial values ​​should be assigned to each row.
When the function is called, the actual parameter of the array parameter is the address of the integer variable; in the function prototype, the formal parameter of the array parameter is the first address of the integer array.
6. There is a technique to jump from the tail of the array to its head is "add 1 modulo".
7. Use the & operation to obtain the address of the variable, and the pointer variable is used to store the address.
8. Before the pointer in the executable statement, it is called the indirect reference operator, and when it is placed in the pointer definition, it is called the pointer definer.
9. The indirect reference operator cannot be used for non-pointer variables, because it can only act on addresses.
Indirect references can be used for both rvalues ​​and lvalues.
The value initialized to the pointer variable is the address value of the pointer type.
Pointers must be initialized before use. Forgetting to assign a value to a pointer is much more dangerous than forgetting to assign a value to an integer variable.
The pointer iPtr++ is not moved back by one bit, but moved back by one unit.
Only addition and subtraction can be used for pointer arithmetic.
10.a[i] is equivalent to * (a+i) is equivalent to iPtr[i] is equivalent to * (iPtr+i)
&a[i] is equivalent to a+i is equivalent to iPtr+i is equivalent to &iPtr[i]
11. The array name itself is a pointer, and its type is a pointer to the array elements.
12. The array name is a pointer constant, which is different from a pointer variable. So assigning a value to an array name is wrong.
13. Constant pointer (pointer to constant): Add const before the type of the pointer definition statement, indicating that the pointed object is a constant. Defining a pointer to a constant only restricts the indirect access operation of the pointer, but cannot stipulate the operation specification of the value pointed to by the pointer itself. const int * pi = &a; the value of a cannot be modified through pi, but pi can be pointed to another variable.
14. Pointer constant: Add const before the pointer name of the pointer definition statement, indicating that the pointer itself is a constant. Must be initialized when defining a pointer constant. char * const pc = "asdf"; its content can be modified through *pc, but the pointer value cannot be changed, that is, it points to another variable.
15. Constant pointer constant (pointer constant pointing to a constant): const int * const cpc = &b; where cpc and *cpc are constants and cannot be operated as lvalues.

16. Array of pointers: Each element in an array is a pointer. char * proname[] = { "Fortran", "C", "C++" };
17. Pointer arrays are different from two-dimensional arrays. The memory representation of an array of character pointers, and the string pointed to by the pointer is of irregular length. Each column of a two-dimensional array must have the same size.
Pointer array names are pointers to pointers (ie secondary pointers).
18. Passing an array to a function is passing a pointer to a function. Passing an array of pointers to a function is passing a secondary pointer to the function.

5. Classes, constructors, static members and friends

1. C++ features: abstraction, encapsulation, inheritance, polymorphism.
2.:: is called the scope specifier, indicating which class a function belongs to or which class a data belongs to. :: can not follow the class name, indicating global data or global functions (ie non-member functions).
3. The data members of the class cannot be initialized.
4. Since the class name is part of the member function name, even if a member function of one class has the same name as a member function of another class, it cannot be considered as overloading.
5. Member functions must be called with objects.
6. The memory space occupied by a class object is determined by the sum of the space occupied by its data members. The member functions of the class do not occupy the memory space of the object.
7. The scope of a class refers to the scope of the class definition and the corresponding member function definition.
8. If a non-type name hides the type name, the type name is available by prefixing. If a type name hides a non-type name, the normal scoping rules apply.
9. C++ stipulates that a name cannot refer to two types at the same time. Non-type names (variable names, constant names, function names, object names, or enumeration members) cannot be duplicated.
10. C++ stipulates that the member function with the same name as the class is a constructor, which is automatically called when an object of this class is created.
11. The constructor has no return type, and the return value is not allowed in the function body, but there can be a valueless return statement "return;".
12. In a class definition, a data member of a class may be an object of another class.
13. If a class object is a data member of another class, in the constructor called by the creation of that class, its constructor is automatically called for the member (object).
14. The destructor has no return type, no parameters, and no overloading. It is only called automatically by the system when the lifetime of the class object ends.
15. The destructor is called in the reverse order of calling the constructor.
16. A constructor without parameters is called a default constructor.
17. C++ stipulates that each class must have a constructor. Without a constructor, no object can be created.
18. If a constructor of a class is not provided (none is provided), C++ provides a default constructor, which is a no-argument constructor, which is responsible for creating objects without doing any initialization work.
19. As long as a class defines a constructor (not necessarily a parameterless constructor), C++ no longer provides a default constructor. That is, if you define a constructor with parameters for a class and want a parameterless constructor, you need to define it yourself.
20. Static objects are the same as static variables. Static objects in file scope are all constructed before the main function starts running. Static objects in the block scope are constructed when the function defining the static object is first entered.
21. Global variables, static data, and constants are stored in the global data area, all class member functions and non-member function codes are stored in the code area, and local variables, function parameters, return data, and return addresses allocated for running functions are stored in the stack area, and the remaining space is used as the heap area.
22. To allocate an object array from the heap, only the default constructor can be called, and no other constructors can be called. An array of objects cannot be allocated if the class has no default constructor.
23. If your class needs a destructor to destroy resources, it also needs a copy constructor.
You can directly call the constructor to generate an unnamed object. Unnamed objects can be passed as arguments to functions, can be used to copy-construct a new object, or can initialize a referenced declaration.
24. The conversion constructor is to define a constructor with one parameter.
25. The operator new allocates heap memory, returns the space of the memory if successful, and returns NULL if it fails. So every time you use operator new to dynamically allocate memory, you should test the return pointer value of new to prevent allocation failure. pName = new char[ strlen(pN) + 1 ]; if ( pName != 0 ) strcpy( pName, pN );
26. Class members declared as static can coexist in the class scope, called static members.
27. Static data members allocate space and initialize outside the class declaration.
28. Public static data members can be accessed by the outside of the class, protected or private static data members can only be accessed by the inside of the class.
29. The static member function definition is the internal implementation of the class and is part of the class definition. It is defined in the same location as a normal member function.
30. A static member function is not associated with any object, so default access to non-static members is not possible.
31. The fundamental difference between a static member function and a non-static member function: a static member function does not have a this pointer, while a non-static member function has a pointer to the current object this.
32. Declare an ordinary function in the class, and mark the keyword friend to become a friend of the class, and can access all members of the class.
33. The location of the friend declaration can be in any part of the class, either in the public area or in the protected area, and the meaning is exactly the same. The friend function definition is outside the class, and is generally placed together with the member function definition of the class.
34. A member function of a class can be a friend of another class.
35. The entire class can be a friend of another class, which is called a friend class. Every member function of a friend class can access protected or private data members in the other class.
36. The term static of static members and static of static storage classes are two concepts, one is about classes, and the other is about the location of memory space and scope limitation. So it is necessary to distinguish between static objects and static members.

6. Multiple Inheritance and Operator Overloading

1. The virtual of virtual inheritance has nothing to do with the virtual of virtual functions.
2. The construction order of multiple inheritance: 1. The constructors of any virtual base class are constructed in the order in which they are inherited. Two, the constructors of any non-virtual base classes are constructed in the order in which they are inherited. Three, the constructors of any member objects are called in the order in which they are declared. Fourth, the class's own constructor.
3. In the inheritance relationship, the private members of the base class are not only hidden from the application, but also hidden from the derived class. The protected members of the base class are only hidden from the application, but nothing is hidden from the derived class.
4. A private or protected derived class is not a subclass, because a non-public derived class cannot do everything the base class can do.
5. Protected inheritance is similar to private inheritance, and the class after inheritance is independent of the base class. Protect inherited class objects, and members of the base class cannot be used in public.
6. When a class is a derived class of two or more base classes, the class names of all base classes must be listed after the derived class name and a colon, and the base classes are separated by commas.
7. The constructor of the derived class must activate all base class constructors and pass the corresponding parameters to them.
8. In a class without inheritance, there is no difference between protected and private control characters. In inheritance, the private of the base class is shielded from all the outside world (including its own derived classes), and the protected control character of the base class is shielded from the application program, but accessible to its derived classes.
9. The operator is a function, except that the operation order and priority cannot be changed, the parameter and return type can be re-specified, that is, it can be overloaded.
10. C++ stipulates that the five operators " . , :: , . * , -> , ?: " cannot be overloaded, nor can new operators be created.
11.operator++() is a unary operator that contains one parameter. ++d <=> d.operator++(); d++ <=> d.operator++(0)
12. C++ stipulates: =, (), [], -> These four operators must be member forms.
13. Using pre-increment, incrementally modifies an object (operand) before returning the object. So when the pre-increment operator operates, the parameter and the returned object are the same.
14. When using post-increment, the original object value must be returned before the increment. To this end, a temporary object is created to store the original object, so that when the operand (object) is incrementally modified, the original value is saved.
15. Conversion operator: operator type name (); it has no return type, because the type name represents its return type, so the return type is redundant.

exercise

1. Multiple choice questions

1. Every C++ program must contain such a function whose function name is (A).
A. main B. MAIN C. name D. function

2. If all members in the class do not use the keywords public, private or protected when they are defined, all members are defined as (C) by default.
A) public B) protected C) private D) static

3. All objects of a class share (D).
A) private data members B) public data members C) protected data members D) static data members

4. The polymorphism supported by dynamic binding is called (D).
A. Virtual function B. Inheritance C. Compile-time polymorphism D. Run-time polymorphism

5. In the following description of overloaded functions, the correct one is (C).
A) Overloaded functions must have different return value types B) The number of formal parameters of overloaded functions must be different C
) Overloaded functions must have different formal parameter tables D) The names of overloaded functions can be different

6. Assume that MyCIass is a class, then in the following function description, (D) is the destructor of the class.
A) void~MyClass(); B)~MyClass(int n); C) MyClass( ); D)~MyClass( );

7. Among the following descriptions about C++ functions, the correct one is (C).
A) An inline function is a function defined inside another function body
B) The last statement in the function body must be a return statement
C) Before calling a function, if the function has not been defined, its prototype must be declared first
D) Compiler The different overloaded forms of the function are distinguished according to the return value type and parameter list of the function

8. Assume that MyCIass is a class, then in the following function description, (C) is the no-argument constructor of this class.
A) void MyClass(); B) ~MyClass(int n); C) MyClass( ); D) ~MyClass( );

9. The following is the function prototype declaration of the overloaded addition operator, where the error is ( A ).
A) MyClass operator+(double,double);
B) MyClass operator+(double,MyClass);
C) MyClass operator+(MyClass,double);
D) MyClass operator+(MyClass,MyClass);

10. Which of the following descriptions of class constructors and destructors is correct (A).
A) Constructors can be overloaded, but destructors cannot be overloaded B) Constructors cannot be overloaded, destructors can be overloaded C) Constructors can be overloaded
, destructors can be overloaded D) Constructors cannot be overloaded, Destructors cannot be overloaded

11. Add the keyword "inline" before the function definition, indicating that the function is defined as ( B ).
A) Overloaded functions B) Inline functions C) Member functions D) Ordinary functions

12. Of the following statements about classes and objects, (C) is incorrect.
A) An object is an instance of a class B) Any object can only belong to a specific class
C) A class can only have one object D) The relationship between classes and objects and the data type are similar to the relationship between variables

13. The role of the class's destructor is (D).
A) As a general member function of a class B) Initialization of a class C) Initialization of an object D) Deletion of an object

14. A class's friend function or friend class can access (D) of that class.
A) private members B) protected members C) public members D) all members

15. In the following description about the characteristics of member functions, (D) is wrong.
A) The member function must be an inline function B) The member function can be overloaded
C) The member function can set the default value of the parameter D) The member function can not set the default value of the parameter

16. Of the following functions, (C) is not a member function of the class.
A) constructor B) destructor C) friend function D) copy constructor

17. In the following description, (B) is wrong.
A) The public members of the base class are still public in the derived class during public inheritance.
B) The private members of the base class are private in the derived class during public inheritance.
C) The protected members of the base class are still public in the derived class during public inheritance. The class is still protected
D) When privately inherited, the public members in the base class are still private in the derived class

18.class A
{ int i, j; public: A(int m, int n): i(m), j(n) { } int Geti() { return i;} }; class B: public A { int k; public: B(int m, int n, int u): A(m, n), k(u) {} void Make( ) { k = i * j; } }; int main() { B b (1, 2, 3); return 0; } Then in the above definition, ( A ) is an illegal expression. A) k=ij; B) int k; C) return i; D) void Make( )

















19. Assuming that CTest is a class, and there is a parameterized constructor with no default value and a parameterless constructor, (B) of this class will be automatically called when the "CTest objTest;" statement is executed.
A) Argument constructor B) No argument constructor C) Copy constructor D) Assignment overload function

20. (D) is not included in the main features of object-oriented programming ideas.
A. Encapsulation B. Polymorphism C. Inheritance D. Functional decomposition, step by step refinement

21. Consider the following function prototype declaration: void testDefaulParam(int a, int b=7, char z='');
The following function call is illegal (C).
A. testDefaulParam(5); B. testDefaulParam(5,8);
C. testDefaulParam(5,'#'); D.testDefaulParam(0,0,'*');

22. Among the following statements, the one that correctly overloads the function int sum(int x, int y) is (C).
A. float sum(int x, int y); B. int sum(int a, int b);
C. float sum(float x, float y); D. double sum(int y, int x);

23. Among the following methods of quoting, (A) is correct.
Known: int a=1000;
A. int &x=a; B. char &y; C. int &z=1000; D. float &t=&a;

24. Knowing class X, when the program executes to the statement: X array[3];, the constructor is called (D) times.
A. 0 B. 1 C. 2 D. 3

25. In the following description about friends, the wrong one is (D).
A. Friend functions can access the private data members of the class
B. The member functions in a friend class of a class are all friend functions of this class
C. Friends can improve the running efficiency of the program
D. Between classes The friendship relationship of

26. The statement about the destructor is incorrect (B).
A.There is one and only one destructor
B. A destructor, like a constructor, can have parameters
C. The function of the destructor is to do some memory cleaning work before the system releases the object
. Destructor does not have any function type

27. You can access the base class member a of the derived class object p in the form of pa outside the class, where a is (D).
A.Privately inherited public members B. Publicly inherited private members
C. Publicly inherited protected members D. public inherited public members

28. In the case of public inheritance, the access rights of non-private members of the base class in the derived class (B)
(A) restricted (B) remain unchanged (C) protected (D) not protected

29. The function of the scope operator "::" is (B)
A. Identify the level of the scope
B. Point out the scope of the scope
C. The size of the given scope
D. Identify which class the member belongs to

30. The statement about the const keyword is wrong (D)
A. const keyword can modify objects and member functions
B. const objects cannot be modified
C. const member functions cannot modify class data members
D. const can be used to describe classes

31. The following description is wrong (A)
A. Before creating an object, static members do not exist
B. Static members are members of a class
C. Static members cannot be virtual functions
D. Static member functions cannot directly access non-static members

2. Fill in the blanks

1. The function that overloads the operator "+" is called operator+.
2. In C++, if the name of the class is CTest, the name of the constructor of this class is CTest().
3. The constructor function is called automatically when an object of the class is created.
4. For the constructor of the derived class, the execution order of the constructor when defining an object is: execute the constructor of the base class first, then execute the constructor of the sub-object class, and finally execute the content in the constructor body of the derived class.
5. The concrete representation of a class is manipulated by creating objects.
6. Assuming that AB is a class, when the statement "AB a[10];" is executed, the number of times the system will automatically call the constructor of this class is 10.
7. In C++, the description symbols for the three inheritance methods are private, public and protected. If no description is added, the default inheritance method is private.
8. To define void fun( ) as a friend function of class A, the statement friend void fun(A &a) should be added to the definition of class A.
9. Operator overloading requires maintaining the original number of operands, priority, and associativity.
10. List two user-defined data types in C++: structure and class.
11. The role of the constructor is to allocate storage space for the object and initialize the data members of the object when the object is created.
12. The composition of a C++ class includes data members and member functions, and friends are not member functions of the class.
A friend function is a non-member function decorated with the keyword friend.

3. Read the program and write the result

1. If there is the following program:
class A
{ int a; public: A(int aa = 0 ) { a = aa; } ~A( ) { cout << "Destructor A!" << a << endl; } };










class B: public A
{ int b; public: B(int aa = 0, int bb = 0): A(aa) { b = bb; } ~B() { cout << "Destructor B!" << b << endl; } }; int main() { B x(5), y(6,7); return 0; } The output of the above program is: Destructor B! 7 Destructor A! 6 Destructor B! 0 Destructor A ! 5




















2. If there is the following program:
#include <iostream.h>
class Point
{ int x, y; public: Point() { x = 0; y = 0; } void SetPoint(int x1, int y1) { x = x1; y = y1; } void DisPoint() { cout << "x=" << x << "," << "y=" << y << endl; } } ; int main() { Point P1; P1. SetPoint(5, 12); P1.DisPoint(); return 0; } The output of the above program is: x=5, y=12 3. If there is the following program: #include <iostream.h> class A { int a; public:A(int aa = 0 )































{
a = aa;
cout << "A(): " << a << endl;
}
};
class B: public A
{
int b;
public:
B(int aa = 0, int bb = 0): A(aa)
{
b = bb;
cout << "B(): " << b << endl;
}
};
int main()
{
B x(5), y(6,7);
return 0;
}
输出结果为:
A( ): 5
B( ): 0
A( ): 6
B( ): 7

class Date
{
public:
Date(int,int,int);
Date(int,int);
Date(int);
Date();
void display();
private:
int month, day, year;
};
Date::Date(int m,int d,int y):month(m),day(d),year(y) { }
Date::Date(int m,int d):month(m),day(d) {year=2009;}
Date::Date(int m):month(m){day=1; year=2010; }
Date::Date( ) {month=1; day=1; year=2010; }
void Date::display(){ cout<<month<<“/”<<day<<“/”<<year<<endl; }
int main( )
{
Date d1(12,31,2009);
Date d2(12,31);
Date d3(1);
Date d4;
d1.display();
d2.display();
d3.display();
d4.display();
return 0;
}
The output result is:
12/31/2009
12/31/2009
1/1/2010
1/1/2010
4. Program to fill in the blanks
1. Please complete the following program
#include // preprocessing command
using namespace std; // use standard namespace std
class Test
{ private: int a; // data member public: Test(int x = 0){ (1) } / / Constructor void Show( ){ cout << "a:" << a << endl; } // Display the value of data member}; int main( ) // Main function main(void) { Test obj(168) ; // define object (2) // display the value of data members return 0; } 2. Please complete the following program #include // preprocessing command using namespace std; // use standard namespace std















class Complex
{ private: double realPart; // real part double imagePart; // imaginary part public: Complex(double real = 0, double image = 0) // constructor { realPart=real; imagePart=image; } double GetRealPart( ) { return realPart; } // return real part double GetImagePart( ){ return imagePart; } // return imaginary part Complex operator+( Complex &a) // overloaded addition operator+ { return Complex( (3) ); // return sum } }; int main( ) // main function main(void) { Complex a(1, 2), b(2, 6), c; // define complex object (4) // complex addition operation




















cout << "a=" << a.GetRealPart() << "+" << a.GetImagePart() << "i" << endl; // display a
cout << "b=" << b. GetRealPart() << "+" << b.GetImagePart() << "i" << endl; // display b
cout << "c=" << c.GetRealPart() << "+" << c .GetImagePart() << "i" << endl; // display c
return 0; // return value 0, return to operating system
}
reference answer: (1) a=x ; (2) obj.Show( );
( 3) realPart + a.realPart, imagePart + a.imagePart (4) c=a+b;

5. Program Design Questions

1. Construct a rectangle class of rectangle, including data members, the coordinates of the lower left corner point (x1, y1) and the coordinates of the upper right corner point (x2, y2); it includes the member function getarea( ) to calculate the area of ​​the rectangle. Complete the class, define a rectangular object in the main function, and calculate and output the area of ​​the rectangular object (10 points)
2. Define two classes, boat and car, both of which have a weight attribute, and define a friend function of the two totalweight(), calculate the sum of the weights of the two. (10 points)

mooc wrong question

insert image description here
insert image description hereinsert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description here
insert image description hereinsert image description hereinsert image description here
insert image description here
insert image description hereinsert image description here
insert image description hereinsert image description here
insert image description here
insert image description here
insert image description here
insert image description here

The difference between the implementation of member functions inside and outside the class:
the implementation inside the class is also called inline function. The inline function is replaced by the code of the inline function body at the calling function. It is not like a general function, which is transferred to be executed. The body of the called function returns to the calling function after execution, which will increase the running speed. The code efficiency of the inline function and the macro definition with parameters is the same, but it is better than the macro definition.
The functions implemented outside the class are called external functions. Their calling process is the same as that of ordinary functions, and their execution efficiency is not as good as that of inline functions. However, external functions can be converted into inline functions by adding the keyword inline before the function. into an inline function.
Member function calls require time and space overhead. For long functions, this overhead is negligible, but for functions with short body codes and frequently called functions, this overhead cannot be ignored. The introduction of inline functions is just In order to solve this problem and improve the running efficiency of the program,
it is not suitable to use the inline function:
(1) If the code in the function body is relatively long, using the inline function will result in high memory consumption costs
(2) If the function body appears loop, then the time to execute the code in the function body is greater than the overhead of the function call.
Function overloading in
a class In the same scope,
the function name is the same,
the function parameter type or number is different
, only the return value is different, it cannot be function overloading

Guess you like

Origin blog.csdn.net/weixin_55085530/article/details/125491566