C++/C must know

Source: Internet
Author: User
Tags array definition

2. What is a "citation"? What are the issues to be aware of and use of "references"?

A: A reference is an alias for a target variable, and the action on the app is exactly the same as the direct action on the variable. When declaring a reference, remember to initialize it. When the reference declaration is complete, the target variable name is equal to two names, that is, the target name and reference name, and the reference name cannot be used as an alias for the other variable names. Declaring a reference is not a new definition of a variable, it simply means that the reference name is an alias of the target variable name, it is not a data type in itself, so the reference itself does not account for the storage unit, and the system does not assign a storage unit to the reference. You cannot create a reference to an array.

3. What are the characteristics of "reference" as a function parameter?

(1) The effect of passing a reference to a function is the same as passing a pointer. At this point, the parameter of the function is used as the real parametric or an alias of the object in the original central melody function, so the operation of the parameter variable in the function is the operation of its corresponding target object (in the central Melody function).

(2) using the parameters of the reference transfer function, in memory does not produce a copy of the argument, it is directly to the actual parameter operation, while using the general variable transfer function parameters, when a function call, you need to assign a storage unit to the parameter, the parameter variable is the copy of the argument variable; Therefore, when the parameter passes the data is large, uses the reference to pass the parameter with the general variable efficiency and occupies the space to be good.

(3) The use of pointers as parameters of the function, although also can achieve with the use of reference, but in the function of the parameter allocation of the same storage unit, and the need to re-use "* pointer variable name" in the form of operations, which is prone to error and poor program reading; On the other hand, at the call point of the keynote function You must use the address of the variable as the argument. And references are easier to use and clearer.

4. When do I need to use "regular reference"?

If you need to use references to improve the efficiency of the program, but also to protect the data passed to the function is not changed in the function, you should use a constant reference. Common Reference declaration method: Const type identifier & reference name = target variable name;

Example 1

int A;
const INT &ra=a;
Ra=1; Error
A=1; That's right

Example 2

string foo ();
void Bar (string & S);
Then the following expression will be illegal:
Bar (foo ());
Bar ("Hello World");

The reason is that both the Foo () and the "Hello World" strings produce a temporary object, whereas in C + + These temporary objects are const types. So the expression above is an attempt to convert an object of a const type to a non-const type, which is illegal.

Reference parameters should be defined as const when they can be defined as const.

5. What are the formats, benefits, and rules that you need to follow to return a value type as a function?

Format: type identifier & function name (parameter list and type description) {//function Body} benefit: No copy of the returned value is generated in memory; (Note: It is for this reason that it is undesirable to return a reference to a local variable.) Because with the end of the local variable's lifetime, the corresponding reference will also be invalidated, resulting in runtime error!

Precautions:

(1) A reference to a local variable cannot be returned. This can be referred to effective c++[1] Item 31. The main reason is that the local variable is destroyed after the function returns, so the returned reference becomes a "no" reference, and the program goes into an unknown state.

(2) You cannot return a reference to the memory that is allocated inside the function. This can be referred to effective c++[1] Item 31. Although there is no passive destruction of local variables, there are other embarrassing situations where you can return a reference to a function's internal new allocation memory. For example, a reference returned by a function is only present as a temporary variable and not given an actual variable, so the space the reference points to (allocated by new) cannot be freed, causing memory Leak. (3) You can return a reference to a class member, but preferably a const. This principle can be referred to effective c++[1] Item 30. The main reason is that when an object's properties are associated with a business rule, The assignment is often related to the state of some other property or object, so it is necessary to encapsulate the assignment in a business rule. If other objects can get a very good reference (or pointer) to the property, the simple assignment of that property will break the integrity of the business rules.

(4) The stream operator overload return value is declared as the function of "reference": Stream operator << and >> the two operators often want to be used continuously, for example: cout << "Hello" << Endl; Therefore, the return value of these two operators should be a stream reference that still supports both operators. Alternative options include returning a stream object and returning a pointer to a stream object. But for a stream object to be returned, the program must recreate (copy) a new stream object, that is to say, two consecutive << operators are actually for different objects! It's not acceptable to anyone. The << operator cannot be used consecutively for returning a stream pointer. Therefore, returning a Stream object reference is the only option. This unique choice is key, it shows the importance of the reference and the irreplaceable, perhaps this is the introduction of the concept of reference in the C + + language is the reason for it. The assignment operator =. This operation, like the Fuchang operator, can be used consecutively, for example: x = j = 10, or (x=10) = 100; The return value of the assignment operator must be an lvalue so that it can continue to be assigned. The reference is therefore the only return value selection for this operator.

Example 3

#i nclude <iostream.h>
int &put (int n);
int vals[10];
int error=-1;
void Main ()
{
Put (0) = 10; The value of the put (0) function as the left value is equivalent to vals[0]=10;
Put (9) = 20; The value of the put (9) function as the left value is equivalent to vals[9]=20;
cout<<vals[0];
cout<<vals[9];
}
int &put (int n)
{
if (n>=0 && n<=9) return vals[n];
else {cout<< "subscript error"; return error;}
}

(5) In some other operators, it is not possible to return a reference: +-*/arithmetic character. They cannot return references, effective c++[1] Item23 detailed discussion of this issue. The main reason is that these four operators do not have side effect, so they must construct an object as the return value, and the optional scheme includes returning an object, returning a reference to a local variable, returning a reference to a new allocated object, and returning a static object reference. According to the preceding reference as the three rules for the return value, the 2nd and 32 scenarios are deprecated. A reference to a static object also causes an error because ((a+b) = = (C+d) is always true. So the only option left is to return an object.

6. What is the relationship between "referencing" and polymorphism?

A reference is another means of producing a polymorphic effect, in addition to pointers. This means that a reference to a base class can point to its derived class instance.

Example 4

Class A;  Class b:class a{...}; b b; a& ref = B;

7. What is the difference between a "reference" and a pointer?

The pointer indirectly operates on the variable it points to after it points to an object through a pointer variable. The use of pointers in the program, the readability of the program, and the reference itself is the alias of the target variable, the operation of the reference is the operation of the target variable. In addition, this is the difference between the function ref and the pointer mentioned above.

8. When do I need to "quote"?

Reference is recommended for the stream operator << and >>, the return value of the assignment operator =, the parameter of the copy constructor, the parameter of the assignment operator =, and other cases.

Above 2-8 reference:http://blog.csdn.net/wfwd/archive/2006/05/30/763551.aspx

18. Overloading (overload) and rewriting (overried, some books are also called "overlays") the difference?

Frequently-tested topics. By definition: overloading: means that multiple functions with the same name are allowed, and the parameter tables of these functions are different (perhaps the number of arguments is different, perhaps the parameter types are different, perhaps the two are different).

Overriding: Refers to a method by which a subclass re-defines a complex virtual function.

From the principle of implementation: overloading: The compiler modifies the name of a function with the names of the same name, based on a different parameter table of the function, and then the functions of the same name are different functions (at least for the compiler). For example, there are two functions of the same name: function func (p:integer): Integer, and function func (p:string): integer; Then the compiler has done a modified function name may be this: Int_func, Str_func. The invocation of these two functions has been determined and is static between the compilers. That is, their addresses are bound (early bound) at compile time, so overloading and polymorphism are irrelevant!

Rewrite: is really related to polymorphism. When a child class has redefined the virtual function of the parent class, the parent class pointer dynamically calls the function that belongs to the subclass according to the different child class pointers assigned to it, so that the function call cannot be determined during compilation (the address of the virtual function of the called subclass cannot be given). Therefore, such a function address is bound at run time (late binding).

19. What is the role of polymorphism?

The main is two: 1. Hide the implementation details, so that the code can be modular, extension code module, implementation of code reuse, 2. Interface reuse: For classes to be inherited and derived, the correct invocation is guaranteed when using a property of an instance of any class in the family.

is C + + type-safe?

Answer: No. Between two different types of pointers can be cast (cast with reinterpret). C # is type-safe.

What code will be executed before the main function executes?

Answer: The constructor for the global object is executed before the main function.

26. Describe how memory is allocated and how they differ?

1) allocation from a static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables, static variables.

2) Create on the stack. When executing a function, the storage units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the instruction set of the processor.

3) allocation from the heap, also known as dynamic memory allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by programmers and is very flexible to use, but the problem is the most.

The difference between 27.struct and class answers: Members of a struct are public by default, and members of a class are private by default. struct and class are functionally equivalent in other respects.

Emotionally, most developers feel that there is a big difference in class and structure. The sensory structure is just like a bunch of open memory bits that lack encapsulation and functionality, and the class is like a live and reliable member of society, it has intelligent services, has a solid packaging barrier and a well-defined interface. Since most people think so, there are only a few methods in your class and there are public data (this kind of thing exists in a well-designed system!). ), you should probably use the struct keyword, otherwise you should use the Class keyword.

29. How is the logical address and physical address converted under the 8086 assembly? (Intel)

Answer: The address given by the general register is the offset address in the segment, the corresponding segment register address *10h+ the address in the General register, and the address is actually to be accessed.

30. Compare the 4 types of conversions in C + +?

Please refer to:http://blog.csdn.net/wfwd/archive/2006/05/30/763785.aspx , with emphasis on static_cast, dynamic_cast and reinterpret_ The difference and application of cast

32. What are the advantages of const versus # define?

Answer: 1) const constants have data types, and macro constants do not have data types. The compiler can perform type safety checks on the former. Instead of only character substitution, there is no type safety check, and the substitution of characters can produce unexpected errors.

2) Some integrated debugging tools can debug const constants, but cannot debug macro constants.

34. Overloading, overwriting, and hiding differences for class member functions?

Answer:

A. Features that are overloaded with member functions:

(1) The same range (in the same Class), (2) The function name is the same, (3) the parameters are different; (4) The virtual keyword is optional.

B. Overwrite refers to a derived class function overriding a base class function, characterized by:

(1) different ranges (in the derived class and the base Class), (2) The function name is the same, (3) The parameters are the same; (4) The base class function must have the virtual keyword.

C. " Hide refers to a function of a derived class that masks a base class function with the same name as the following rule:

(1) If the function of the derived class has the same name as the function of the base class, but the parameters are different. At this point, the function of the base class is hidden, regardless of the virtual keyword (Note that it is not confused with overloading).

(2) If the function of the derived class has the same name as the function of the base class, and the parameters are the same, the base class function does not have the virtual keyword. At this point, the function of the base class is hidden (be careful not to confuse the overlay)

When the main function is finished, is it possible to execute a piece of code and give a description?

Answer: Yes, you can register a function with _onexit, which will execute after main int fn1 (void), fn2 (void), fn3 (void), fn4 (void);

void Main (void)
{
String Str ("Zhanglin");
_onexit (FN1);
_onexit (FN2);
_onexit (FN3);
_onexit (FN4);
printf ("This is executed first.\n");
}
int fn1 ()
{
printf ("next.\n");
return 0;
}
int fn2 ()
{
printf ("executed");
return 0;
}
int Fn3 ()
{
printf ("is");
return 0;
}
int Fn4 ()
{
printf ("this");
return 0;
}
The _onexit function is passed the address of a function (func) to being called when the program terminates normally. Successive calls to _onexit create a register of functions that is executed in LIFO (last-in-first-out) Order. The functions passed to _onexit cannot take parameters.

44. Multiple-Inheritance memory allocation problems: For example, a class A:public class B, public class C {} What is the memory structure of a?

This is compiler-dependent, and the details of different implementations may be different.

It is quite simple to not consider virtual functions or virtual inheritance, otherwise it is quite complicated.

Refer to the in-depth exploration of the C + + object model, or:http://blog.csdn.net/wfwd/archive/2006/05/30/763797.aspx

45. How can I tell if a single linked list is a ring? (Note that you cannot use the flag, you can use up to two extra pointers)

struct Node {char val; node* next;}

BOOL Check (const node* head) {}//return false: No ring; true: Ring

One way O (n) is to (make two pointers, one step at a time, one step at a time, if there is a ring, the two must overlap, and vice versa):

BOOL Check (const node* head)
{
if (head==null) return false;
Node *low=head, *fast=head->next;
while (Fast!=null && fast->next!=null)
{
low=low->next;
fast=fast->next->next;
if (low==fast) return true;
}
return false;
}

1. Is it a parent class that writes a virtual function that can be polymorphic if the subclass overrides its function without virtual?

The virtual modifier is inherited by stealth.

Private is also integrated, only the derived class does not have access to it. Virtual add-in space with no subclass has all the variables of the parent class (except static)

Only one entity exists for the same function (except inline)

Subclasses covering its functions do not add virtual, can also achieve polymorphism.

In the subclass space, there is a private variable of the parent class. Private variables cannot be accessed directly.

3. Please describe the Windows memory management method briefly.

Memory management is an important part of the operating system, two or three words I am afraid no one can say it is not clear ~ ~ I first say a general, I hope to be able to give it up. When the program runs, it needs to read the code from memory. The location of the code must be in physical memory to be able to be run, because the current operating system has a very many programs running, memory can not be completely put down, so the concept of virtual memory. Put the unused pieces of the program into the virtual memory, when needed to use it in the load master (physical memory). This is what memory management needs to do. Memory management There's another thing to do: compute the physical location of the program fragment in main memory for CPU scheduling.

Memory management is block-managed, page-managed, Segment-and section-page-managed. Now commonly used section page Management block management: The main memory is divided into a large chunk, when the required program fragment is not in main memory to allocate a piece of main memory space, the program fragment load into the storage, even if the required program slice only a few bytes can only be allocated to it. This creates a lot of waste, with an average of 50 of memory wasted, but easy to manage.

Page management: The main memory is divided into one page, each page of space is much smaller than a piece of space, it is obvious that the space utilization of this method is much higher than the block-type management.

Segment management: The main memory is divided into a paragraph, each section of space and a page more than one page of space, this method in space utilization is much higher than page management, but there is another disadvantage. A program fragment may be divided into dozens of segments, so that a lot of time will be wasted on computing the physical address of each segment (the computer is the most time-consuming people know that I/O bar).

Section-page Management: combines the benefits of segment management and page management. The main memory is divided into several pages, and each page is divided into several paragraphs. The benefits are obvious, so I don't have to say more.

Various memory management have its own method to calculate the program fragment in main memory physical address, in fact, are very similar.

This is just a ballpark, not enough to illustrate the fur of memory management. No matter which operating system the book has a detailed explanation

2. Is there a problem with the two sizeof usages in the following code? [C Easy]

void uppercase (char str[])//Convert lowercase letters in STR to uppercase
{
for (size_t i=0; i<sizeof (str)/sizeof (str[0]); ++i)
if (' A ' <=str[i] && str[i]<= ' z ')
Str[i]-= (' A '-' a ');
}
Char str[] = "ABcDe";
cout << "str character length:" << sizeof (str)/sizeof (str[0]) << Endl;
Uppercase (str);
cout << str << Endl;

Answer: There is a problem with sizeof in the function. According to the syntax, sizeof can only measure the size of a static array for arrays, and cannot detect dynamically allocated or external array sizes. The str outside the function is a statically defined array, so its size is 6, the function of STR is actually just a pointer to a string, there is no additional information related to the array, so the siz EOF is used to only see it as the pointer, one pointer is 4 bytes, so returns 4.

3. Non-C + + built-in type A and B, in which cases B can be implicitly converted to a? [C + + medium]

For:

A. Class b:public a {...}//B public inherits from a, can be indirectly inherited

B. Class B {operator a ();}//b implements the conversion of implicit conversion to a

C. Class A {A (const b&);}//A implements the Non-explicit parameter as B (can have other parameters with default values) constructor

D. a& operator= (const a&);//assignment operation, although not an authentic implicit type conversion, can also be used to calculate a

4. What is wrong with the following code? [C + + easy]

struct Test
{
Test (int) {}
Test () {}
void Fun () {}
};
void Main (void)
{
Test A (1);
A.fun ();
Test b ();
B.fun ();
}

A: variable b defines an error. The object is defined by the default constructor, and no parentheses are required.

5. What is wrong with the following code? [C + + easy]

cout << (true?1: "1") << Endl;

Answer: Ternary expression "? : The two operands after the question mark must be of the same type.

6. Can the following code be compiled and passed? [C + + easy]

unsigned int const SIZE1 = 2;
Char str1[size1];
unsigned int temp = 0;
CIN >> Temp;
unsigned int const SIZE2 = temp;
Char str2[size2];

A: STR2 defines an error, size2 a non-compiler period constant, and the array definition requires that the length be a compile-time constant.

7. What are the errors of the following methods for iterating through array arrays? [STL Easy]

Vector array;
Array.push_back (1);
Array.push_back (2);
Array.push_back (3);
For (Vector::size_type i=array.size ()-1; i>=0;-I.)//REVERSE Traversal array
{
cout << Array[i] << Endl;
}

A: First, the array definition is incorrect, and the type parameter:vector<int> array should be added. The second vector::size_type is defined as unsigned int, which is the unsigned number, so that the I of the loop variable is 0 o'clock minus 1 and becomes the largest integer. Causes the loop to lose control.

8. Output statements in the following code output 0, why? [C + + easy]

struct CLS
{
int m_i;
CLS (int i): m_i (i) {}
CLS ()
{
CLS (0);
}
};
CLS obj;
cout << obj.m_i << Endl;

Answer: No. It is the user behavior to call the parameter constructor inside the default constructor instead of the compiler behavior, that is, only the function call is executed, and no subsequent initialization expression is executed. The initialization expression is called only with the corresponding constructor when the object is generated.

9. What class member functions are generated by default for empty classes in C + +? [C + + easy]

For:

Class Empty
{
Public:
    Empty ();                          // Default constructor
    Empty (const empty&);            //Copy constructor
    ~empty ();                         //Destructors
     empty& operator= (const empty&); Assignment operator
    empty* operator& ();               //Address operator
    const empty* operator& () const;  //accessor operator Const
};

10. What do the following two output statements output separately? [C + + difficult]

float a = 1.0f;
cout << (int) a << Endl;
cout << (int&) a << Endl;
cout << boolalpha << ((int) A = = (int&) a) << Endl; Output what?
float B = 0.0f;
cout << (int) b << Endl;
cout << (int&) b << Endl;
cout << boolalpha << ((int) b = = (int&) b) << Endl; Output what?

Answer: Output false and true respectively. Note the application of the conversion. (int) A actually constructs an integer number with a floating point number A as a parameter, the integer value is 1, and (int&) a tells the compiler to look at a as an integer (without making any substantial conversions). Because 1 is stored as an integer and stored in floating-point form, its memory data is not the same, so the two differ.

The two conversion meanings of B are the same as above, but the 0 integer form and the floating-point form have the same memory data, so in this special case, they are equal (only in numerical sense).

Note that the output of the program will show (int&) a=1065353216, how does this value come from? As already mentioned, 1 is stored in memory as a floating-point number, as specified by ieee754, whose contents are 0x0000803f (byte inversion is considered). This is the value of the memory unit that the a variable occupies. When (int&) a appears, it is equivalent to telling it the context: "Treat this address as an integer!" Don't care what it turns out to be. "In this way, the content 0x0000803f is interpreted as integers, and the value is exactly 1065353216 (decimal number).

By looking at the assembly code, you can confirm that "(int) A is equivalent to re-constructing a value equal to a number of integers", whereas (in t&) is merely expressing a type of information, meaning to choose the correct overloaded version for cout<< and = =.

11. What is wrong with the following code? [STL Easy]

typedef vector Intarray;
Intarray Array;
Array.push_back (1);
Array.push_back (2);
Array.push_back (2);
Array.push_back (3);
Delete all 2 of array arrays
For (Intarray::iterator Itor=array.begin (); Itor!=array.end (); ++itor)
{
if (2 = = *itor) array.erase (itor);
}

A: There are also problems with missing type parameters. In addition, each time you call "Array.erase (Itor);", the contents of the deleted element move forward automatically, resulting in an iterative drain item, which should be removed after deleting an item so that the itor--continues to traverse from the next element that has moved forward.

12. Write a function to complete the copy between the memory. [Consider whether the problem is comprehensive]

For:

void* mymemcpy (void *dest, const void *SRC, size_t count)
{
    char* pdest = Static_cas T<char*> (dest);
    const char* PSRC = Static_cast<const char*> (SRC);
    if (pdest>psrc && pdest<psrc+cout) can take this into account
    {
        for (size_t i=count-1; i!=-1; i.)
                 Pdest[i] = psrc[i];
   }
    Else
    {
        for (size_t i=0; i <count; ++i)
            pdest[i] = psrc[i];
   }
    return dest;
}

C++/c must know

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.