C + + Primer reading notes 1

Source: Internet
Author: User

1, enter the file terminator in the Windows system method is CTRL + Z

2, how to choose the type?

1) Use a unsigned type when Youknow then the values cannot be negative

2) use an int for integer arithmetic.short are usually too small and, in practice, long often have the same size asint. If your data values is larger than the minimum guaranteed size of an int,then use long long.

3) do not use plain char or boolin arithmetic expressions. Use them for characters or truth values. Computations using char is especially problematic because Char was signed onsome machines and unsigned on others. If you need a tiny integer, explicitlyspecify either signed char or unsigned char.

4) use double for floating-pointcomputations; Float usually does not has enough precision, and the cost ofdouble-precision calculations versus single-precision is NEGL Igible. In Fact,on some machines, double-precision operations is faster than single. Theprecision offered by long double usually are unnecessary and often entailsconsiderable run-time cost.

Signed char c2 = n;   Assuming 8-bit chars, the value of C2 is undefined

3, If We assign Anout-of-range value to a object of signed type, the result is undefined. Theprogram might appear to work, it might crash, or it-might produce garbagevalues.

4, Caution:don ' t Mix signed and Unsigned Types.

5, ' a '//character literal

"Helloworld!" string literal

The type of a string literal is an array of constant chars. Thecompiler appends a null character (' + ') to every string liter Al. Thus, theactual size of a string literal is one more than its apparent size. Forexample, the literal ' a ' represents the single character A, whereas the StringLiteral "a" represents an array of both CH Aracters, the letter A andthe null character.

Multiline string literal std::cout << "a really, really long string literal"             <span style= "White-space:pre "></span>      " that spans lines "<< Std::endl;

6, when you write a long literal,use the uppercase L; The lowercase letter l was too easily mistaken for Thedigit 1.

7, the word nullptr is a pointerliteral.

8, initialization is notassignment. Initialization happens when a variable was given a value when it iscreated. Assignment obliterates An object ' s current value and replaces Thatvalue with a new one.

9. The generalized use of curlybraces for initialization is introduced as part of the new standard. This formof initialization previously had been allowed only in more restricted ways,this form of initialization is Referre D to as list initialization.

When used with variables of built-in type, this form ofinitialization have one important property:the compiler would not le T US listinitialize variables of built-in type if the initializer might leads to the lossof information:

Long double ld = 3.1415926536; int A{ld}, b = {ld}; error:narrowing conversion required int C (LD), d = ld;   Ok:but value would be truncated
10, We recommend initializing everyobject of built-in type. It isn't always necessary, but it's easier and Saferto provide an initializer until you can be certain it's safe to OMI T Theinitializer.

11, a declaration makes a name known to the program. A file that wants touse a name defined elsewhere includes a declaration for that name. Adefinition creates the associatedentity.

extern int i;   Declares but does not define I int J;          Declares and defines jextern double pi = 3.1416; Definition

It is an error to provide an initializer on a externinside a function.

Note: Variables must be defined exactly once and can be declared manytimes.

12. Warning:It Isalmost always a bad idea to define a local variable with the same name as Aglobal variable that the function uses or Might use.

13. The type of a reference and theobject to which the reference refers must match exactly. Moreover, for Reasonswe ' ll explore in§2.4.1, a reference could be bound only to an object, not to aliteral or to the Resul T of a more general expression:

int &refval4 = ten;   Error:initializer must is an object double dval = 3.14; int &REFVAL5 = Dval; Error:initializer must is an int object
14, A Pointeris a compound type the "points to" another type. Like References, pointers is used forindirect access to other objects. Unlike a reference, a pointer is an object inits own right. Pointers can assigned and copied; A single pointer can pointto several different objects over its lifetime. Unlike a reference, a pointerneed not being initialized at the time it is defined. Like other built-in types,pointers defined at block scope has undefined value if they is notinitialized.

15. There is several ways toobtain a null pointer:

int *p1 = nullptr; equivalent to int *p1 = 0;int *p2 = 0;       Directly initializes p2 from the literal constant 0//must #include cstdlibint *p3 = NULL;    equivalent to int *p3 = 0; Modernc++ programs generally should avoid using NULL and use nullptr instead.

16, A reference is not A object. Hence, we are not having a pointer to a reference. However, because a pointer Isan object, we can define a reference to a pointer:

int i = 42;int *p;        P is a pointer to intint *&r = p;   R is a reference to the pointer PR = &i; R refers to a pointer; Assigning &i to R makes P point to I *r = 0; dereferencing r yields I, the object to which P points; Changes I to 0

The easiest wayto understand the type of r is to the read the definition right to left. The symbolclosest to the name of the "the variable" in the "The & in &r" is theone that have the most immediate eff ECT on the variable ' s type. Thus, we knowthat R is a reference. The rest of the declarator determines the type to WHICHR refers. The next symbol, * in this case, says the type R refers to is Apointer type. Finally, the base type of the declaration says that R was areference to a pointer to an int.

17, Because We can ' t change thevalue of a const object after we create it, it must is initialized. As usual,the initializer May is an arbitrarily complicated expression:
const int i = Get_size ();  Ok:initialized at run time const int j =;          Ok:initialized at compile time const int k;               Error:k is uninitialized const

Among theoperations that Don's change the value of a object is Initialization-when weuse a object to initialize another object, it doesn ' t matter whether either orboth of the objects is consts:

int i = 42; const int CI = i;    Ok:the value in I was copied into ci int j = ci;          Ok:the value in CI was copied into J
18
file_1.cc defines and initializes a const that's accessible to other files extern const int bufSize = FCN (); file_1.h extern const int bufSize; Same bufSize as defined in file_1.cc

Note: To share Aconst object among multiple files, you must define the variable as extern.

19. References to const

const int CI = 1024; const int &R1 = CI;   Ok:both reference and underlying object is const R1 =;              ERROR:R1 is a reference to constint &r2 = CI;         Error:non Const Reference to a const object<strong></strong>

We noted Thatthere is, exceptions to the rule, the type of a reference must matchthe type of the object to which I T refers. The first exception is the so we caninitialize a reference to const from all expression that can be converted (§2.1.2, p. 35 ) to the type of the reference. In particular, we can bind areference to const to a Nonconst object, a literal, or a more generalexpression:

int i = 42; const int &R1 = i;      We can bind a const int& to a plain int object const int &R2 =;     OK:R1 is a reference to const const INT &R3 = r1 * 2;  OK:R3 is a reference to const int &R4 = r1 * 2;        ERROR:R4 is a plain, non const referencedouble dval = 3.14; const int &ri = Dval; "= ="    Const int temp = Dval;   Create a temporary const int from the double const int &ri = temp;    Bind RI to that temporary
20. Pointers and Const
Const double PI = 3.14;   PI is const; Its value could not be changed double *ptr =π        //error:ptr are a plain pointer const double *CPTR =π//ok:cptr may p Oint to a double this is const *CPTR =;               Error:cannot Assign to *cptrdouble dval = 3.14;       Dval is a double; Its value can changed cptr = &dval;             Ok:but can ' t change dval through CPTR
21, A constant expression is anexpression whose value cannot the change and the can be evaluated at compile time. A literal is a constant expression. A const object is initialized from Aconstant expression is also a constant expression.
const int max_files =;    Max_files is a constant expression const int limit = Max_files + 1; Limit is a constant expressionint staff_size =;       Staff_size is not a constant expression const int sz = Get_size (); SZ is not a constant expression

Under the new standard, we can ask the compiler to verify that avariable are a constant expression by declaring the Variabl E in a constexprdeclaration. Variables declared as constexpr is implicitly const and must beinitialized by constant expressions:

constexpr int MF =;        is a constant expression constexpr int limit = MF + 1; MF + 1 is a constant expression constexpr int sz = size ();    Ok if size is a constexpr function

Generally, it Isa good idea to the use CONSTEXPR for variables so intend to use as constantexpressions.

22, A type aliasis a name, a synonym for another type.

We Candefine A type alias in one of the ways. Traditionally, we use a typedef:

typedef double wages;  Wages is a synonym for doubletypedef wages base, *p; Base is a synonym for double, pfor double*

The new standard introduced a second-define a typealias, via an alias declaration:

Using SI = Sales_item; SI is a synonym for Sales_item
23. pointers, const, and Type Aliases
typedef char *pstring; Const Pstring CStr = 0; CStr is a constant pointer to char const pstring *PS;      PS is a pointer to a constant pointer to Char
24

Auto i = 0, *p = &i;   OK:I is int and p are a pointer to int auto SZ = 0, pi = 3.14; Error:inconsistent types for sz and piint i = 0, &r = i;  Auto A = R; A is an int (R was an alias for I, which have type int) const int CI = i, &cr = CI;  Auto B = ci;  b is a int (top-level const in CI is dropped) auto C = CR;  c is a int (CR is a alias for CI whose const is top-level) Auto d = &i; D is an int* (& of a int object is int*) Auto E = &ci; E is the const int* (& of a const object is low-level const) const auto F = CI; deduced type of CI is int;       F has type const intauto &g = CI;       G is a const int& this is bound to ci auto &h = 42; Error:we can ' t bind a plain reference to a literal const auto &AMP;J = 42;    Ok:we can bind a const reference to a Literalauto k = ci, &l = i; K is int; L is int& auto &m = ci, *p = &ci; M is a const int&;p are a pointer to const INT//Error:type deduceD from I was int; Type deduced from &AMP;CI is const int auto &n = i, *p2 = &ci;

25, Etimes We want to define avariable with a type, the compiler deduces from an expression but does notwant to use that Expression to initialize the variable. For such cases, the NewStandard introduced a second type specifier, Decltype, which returns the typeof of its operand. The compiler analyzes the expression to determine it type butdoes not evaluate the expression:

Decltype (f ()) sum = x; Sum has whatever type F returns

The Decltypehandles top-level const and references differs subtly from the. When the expression to which we apply decltype are a variable, decltype returnsthe type of that variable, including Top-lev El Const and references:

const int CI = 0, &cj = ci; Decltype (CI) x = 0; X has type const decltype (CJ) y = x; Y has the type Const int& and is bound to X Decltype (CJ) Z;     Error:z is a reference and must be initialized

Decltypeand References

Decltype of an expression can is a reference type int i = a, *p = &i, &r = i; Decltype (r + 0) b;  Ok:addition yields an int; B is an (uninitialized) int decltype (*p) C;     ERROR:C is int& and must be initialized//decltype of a parenthesized variable are always a reference decltype ((i)) D;    Error:d is int& and must be initialized Decltype (i) e;      Ok:e is an (uninitialized) int

Remember that Decltype ((variable)) (note,double parentheses) was always a reference type, but Decltype (variable) was Aref Erence type only if variable is a reference.

C + + Primer reading notes 1

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.