C ++ basic details 2

Source: Internet
Author: User

1. in terms of reference and pointer concepts, reference (&) is not an object, but an alias of an existing object. Reference cannot be rebound to another object, so reference must be initialized. (Similar to const, once defined, it cannot be modified, so it must be initialized .) Both references and pointers enable indirect access to other objects. The difference is that the pointer itself is an object, which allows assignment and copying of the pointer. the pointer does not need to assign an initial value when it is defined. For the reference concept, we can use this code to deepen our impression: int ival = 12; int * p = & ival; int & refval = ival; int * p1 = & refval; & in int & refval = ival; & represents the reference declaration symbol, while & in int * p1 = & refval; & represents the address. As shown in watch, we can see the values of the pointers p and p1 (the address value 0x0039F1D8) and the values pointed to by the two pointers (12) it is the same (in fact, it is a bit nonsense, since both pointers point to the same address, the value is the same), that is, ival is equivalent to its reference refval. Note: although the pointer p1 is initialized to & refval, the values & refval and & ival are different, that is, refval and ival are stored on different addresses in the memory, however, after int * p1 = & refval is initialized, the value stored on the p1 pointer is not the address of refval, but the address of the ival variable referenced by refval. Therefore, it is clearer here that the role of the quote is equivalent to that of the endorser. What the endorser says represents the original object and has nothing to do with the quote itself. Because the reference is not an object, there is no pointer to the reference. Basically, after int * p1 = & refval, the value of p1 is actually a conceptual supplementary evidence of the ival address. However, pointer references exist. 2. If a const uses an object to initialize another object, it doesn't matter whether it is a const. The constant feature is only used to limit that it cannot be modified after initialization. To share a const object in multiple files, you must add the extern keyword before the definition of the variable. 3. c-style string is not a type, but a conventional writing method formed to express and use the string, strings written in this habit are stored in the character array and ended with null characters ('\ 0. Char ca [] = {'C', '+', '+'}; cout <strlen (ca) <endl; in the preceding example, although ca is a character array, it does not end with '\ 0', so the output result of this Code is unknown. During execution, the strlen function may keep searching forward along the location of the ca in the memory until '\ 0' is encountered. The only difference is: char ca [] = {'C', '+', '+', '\ 0'}; cout <strlen (ca) <endl; in order to ensure that the output result is 3. two character arrays are defined to describe the following: char ca1 [] = "string 1"; char A2 [] = "string 2"; because the array is used, actually, the pointer to the first element of the array is used. Therefore, we cannot compare the two character Arrays Using statements such as if (Cache <Ca 2) or using statements such as cache + Ca 2 to concatenate strings. We must use strcmp to compare strings; Use strcpy and strcat to copy and connect strings, and when using strcpy and strcat functions, we need to carefully check the size of the character array: char sumStr [40]; // pay attention to the size of the array, during debugging, I remembered the recent joke strcpy (sumStr, ca1), strcat (sumStr, "-"), strcat (sumStr, (ps: when compiling on vs2013, the compiler directly tells me: 'strcpy': This function or variable may be unsafe. consider using strcpy_s instead char sumStr [40]; strcpy_s (sumStr, ca1); strcat_s (sumStr, "-"); strcat_s (sumStr, Ca 2); it is worth noting that strcpy_s and strcat_s are more secure functions released by Microsoft in subsequent versions of VS, rather than in the standard library. Therefore, we recommend that you use string to ensure portability) 4. function return type cannot be an array type or function type, but can be a pointer to an array or function. 5. avoid copying function parameters by referencing. Copying large class objects or containers has a low validity rate. Some types (such as IO type) do not support object copying at all, in this case, reference parameters must be used. In addition, to avoid modifying real parameters in the function, we can use constant reference. Bool cmp_length (const string & s1, const string & s2) {return s1.size ()> s2.size () ;}in addition, good habits are :&, * The symbols and parameter names should be written together. Do not write them together with the type to avoid misunderstanding. 6. Class constructor: const cannot be used for const. The compiler automatically generates a default no-argument constructor only when the class does not declare any constructor. Therefore, once we define Other Default constructors, the class will not have the default constructor unless we define a non-parameter constructor. If a class contains a member of the built-in or composite type, this class is suitable for the use of the default constructor of the synthesis only when all these Members have an initial value in the class. The new C ++ 11 standard allows the use of = default to require the compiler to generate default constructors. In most cases, there is no difference in the effect of using a value assignment statement in the constructor's function body by using the constructor to initialize the list or providing parameters. However, for const and reference, such operations must be handled through const initialization. The following process is incorrect: copy the Code class A {public: A () {// error message: constant member B and reference member c do not provide the initial value B = 0; // error, read-only cannot modify c = 0; // not initialized} private: int a; const int B; int & c ;}; the correct way to copy the code is to use the constructor to initialize the list: copy the Code class A {public: A (int x): B (x), c (x) {} private: int a; const int B; int & c;}; copy the code friend (friend): The friend statement only sets the access permission, it is not a function declaration in the general sense. If we want users of the class to be able to call a friend function, we must specify this function for declaration outside the user's life. Although many compilers do not force you to declare your functions outside the class before they are used, it is best to provide an independent declaration of a function and try not to make the program dependent on the compiler. In addition to common non-member functions, you can also use member functions of classes and classes. In addition, the youyuan function does not have the transmitter. For example, Class A declares that Class B is A friend of Class A, and Class B declares that class C is A friend of Class B. Therefore, we cannot simply consider C as A friend of Class. That is to say, each class needs to control its own membership class and membership function. You can define functions in the class. However, even if we put the definition of a friend function inside the class, we must first declare this function outside the function before calling this friend function. Run the following code: copy the Code class X {friend void f () {// function body} X () {f () ;}// error C3861: "f ": unable to find the identifier void g () ;}; void X: g () {f () ;}// error C3861: "f": unable to find the identifier void f (); if you copy the code and place the f declaration before class X definition, no error will be reported. Copy the code void f (); // declare advance class X {friend void f () {// function body} X () {f ();} // compiled by void g () ;}; void X: g () {f () ;}// compiled by copying the code to variable data members: in some cases, we hope to modify a data member even in the const member function. We can do this by adding the mutable keyword when declaring the variable: copy the Code class Screen {public: void some_member () const; void print_count (); private: mutable size_t count = 0;}; void Screen: some_member () const {++ count;} void Screen: print_count () {cout <count <"";} int m Ain (array <System: String ^> ^ args) {Console: WriteLine (L "Hello World"); Screen item = Screen (); item. print_count (); // outputs 0 items. some_member (); item. print_count (); // output 1} copy the code scope: the following code: You can use the Class Name: member variable, or :: to forcibly access the replication code int param = 2; class Scorp {public: void print (int param) {cout <param <endl; // The cout scope <Scorp: param <endl; // The scope in the class, which is the same as this-> param cout <: param <endl; // out-of-class scope} private: int para M = 1 ;}; int main (array <System: String ^> ^ args) {Console: WriteLine (L "Hello World"); Scorp scorp = Scorp (); scorp. print (3); // [param] Output 3, [Scorp: param] Output 1, [: param] Output 2} copy the Code Conversion constructor: if the constructor only accepts one parameter, there is an implicit conversion mechanism for this type: implicit conversion from the constructor parameter type to the class type. Run the following code: copy the Code class A {public: A (int param) {a = param;} const void print (const A & item) const {cout <item. a <"[pay attention to another a] -->" <a <endl;} private: int a; int B; int c ;}; int main (array <System:: String ^> ^ args) {A a_instance = A (6); a_instance.print (9);} the output result of the copied code is: 9 [note another a] --> 6. That is to say, when the print function is executed, item. a equals 9, and a equals 6. Note that there are two constructor executions. The first is to define a_instance and the param is 6 at the time of initialization. The second is to call the_instance.print (const A & item) function, note: The parameter here is A constant reference. Therefore, the implicit conversion mechanism can be used to input the parameter (integer) of the constructor of A's single parameter ), this method is used for implicit processing: the compiler automatically calls the corresponding constructor through the given int type 9 to create an object of type A, and the generated temporary object is passed to the print function, and used as an item in the function body. the value of a is 9. In addition, note that the built-in int type of our parameter is used here, so we can use the literal parameter print (9) during processing. If the unique parameter of the constructor is not of the built-in type but is of another type such as string, it cannot be directly written as print ("9") during processing, but is written in two sentences: string str = "9"; a_instance.print (str); the reason is that when this non-built-in type is used, the input is "9 ", in fact, the default constructor string ("9") of string is called for one conversion, while the class type conversion is only allowed once. The built-in types such as int do not have the so-called default structure conversion operation. We can also write a_instance.print (string ("9") together "))

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.