My C + + notes (sharing and protection of data)

Source: Internet
Author: User
Tags function prototype

*sharing and protection of data:*1. Scope:* Scope is an identifier in the program body that is valid in the area. C++The scope of identifiers in a function is prototype scope, local scope (block scope), class scope, and namespace scope. * (1). Function prototype Scope:* Function prototype scope is the smallest scope in C + + and must include the type description of the formal parameter in the function prototype. When a function prototype is declared, the scope of the formal parameter is the scope of the function prototype. Such as:DoubleAreaDoubleradius), the scope of the identifier radius is between the parentheses of the function area parameter list. *since it is only the formal parameter types that function in the formal parameter list of a functional prototype, identifiers do not work and are therefore omitted in the program, but for the readability of the program it is usually necessary to give the formal parameter identifier when the function prototype is declared. * (2). Local scope:*The scope of a parameter in a function parameter list begins at the declaration in the formal parameter list and ends at the end of the body of the function; A variable declared in the body of a function that begins at the declaration, until the closing of the block at which the declaration resides, and a variable with local scope is also known as a local variable. * (3). Class Scope:The * class can be thought of as a collection of well-known members, with the class X member M having a class scope and access to M in 3: If the identifier of a local scope with the same name is not declared in the member function of X, the member M can be accessed directly within the function, either through an expression x.m or x::m. The most basic method of accessing object members in a program; by ptr->An expression such as M, where PTR is a pointer to an object of Class X. * (4). Namespace scope:*A large program usually has different modules, and different modules may be developed by different people. Duplicate names can occur between classes and functions in different modules. Namespaces will eliminate these errors. Syntax structure:*namespacenamespace Name {*//various declarations within a namespace (function declarations, class declarations 、。。。 );* }*A namespace determines a namespace scope, which is the namespace scope for all identifiers declared within that namespace that do not belong to the previously mentioned scopes. The identifiers declared in the current namespace can be referenced directly inside the namespace, and if you need to reference identifiers for other namespaces, you need to use the following syntax:*namespaces:: Identifiers**namespacesomens{*classsomeclass{...};* };*If you want to refer to the class name SomeClass or function name SomeFunc, you need to use the following method:*Somens::someclass obj;* Sometimes it is too verbose to use such a namespace qualifier in front of identifiers, in order to solve this problem, C + +the using statement is also provided with two types of using statements:*usingnamespaces:: Identifiers;*using namespaceThe name of the namespace;*namespaces are also allowed to be nested:*namespaceouterns{*namespaceinnerns{*classsomeclass{...};* }* }*referring to the SomeClass class, you need to use the Outerns::innerns::someclass syntax;*In addition, there are two more special namespaces:*Global Namespaces and anonymous namespaces. The global namespace is the default namespace, and identifiers declared outside of the namespace that are declared are in a global namespace, and anonymous namespaces are namespaces that do not have names that require the declaration to be displayed. The statement reads as follows:*namespace{*various declarations within the anonymous namespace (function declaration, class declaration 、...);* }*variables with namespace scope are also called global variables;**2. Object lifetime:* (1). Static lifetime:* If the lifetime of an object is the same as the run time of the program, it is said to have a static lifetime, and objects declared in the namespace scope have a static lifetime. If you declare an object with a static lifetime in a local scope inside the function, use the keyword static. Such as:Static inti;*The amount of a static variable in a local scope is that it does not produce a copy with each function call, nor does it fail as the function returns. That is, when a function returns, the next time it is called, the variable is the last value. Even if a recursive call occurs, a new copy of the variable is not created, and the variable is shared between each invocation. * (2). Dynamic lifetime:*The local lifetime object is born at the declaration point and ends when the declaration is executed. The class member object also has its own lifetime. member objects without static adornments have their lifetimes consistent with the lifetime of the object to which they belong. **3static members of the. Class:*in structured programming, the basic unit of a program module is a function, so the sharing of in-memory data between modules is achieved through the sharing of data between functions and functions, including two paths: parameter passing and global variables. * (1). Static data members:*If a property is common to the entire class and does not belong to any specific object, a static member is declared with the static keyword. Static members have only one copy of each class, which is maintained and used by all objects in the class, thus enabling data sharing between different objects of the same category. A class property is a data item that describes the common characteristics of all objects of a class, and for any object instance, its property values are the same for static data members with static lifetimes. Because a static data member does not belong to any one object, it can be accessed through the class name, and the general syntax is:*class Name:: identifier;** (2). Static function Members:*static member functions can directly access the static data and function members of the class. Instead of accessing non-static members, you must pass the object name. *classa{ Public:Static voidF (a a);Private :intx;};voidA::f (A a) {cout<<x;//This is wrong!cout<<a.x;//Accessing a non-static member of a class in a static member function requires that the object be indicated because the call to the static member function is not a destination object, so you cannot implicitly access the non-static members of the class through the destination object as a non-static member function. }**4. Friend of class:*A friend relationship provides a mechanism for data sharing between the member functions of different classes or objects, the Narimoto function of a class, and the relationship between general functions. In layman's terms, it is a class that proactively declares which other classes or functions are its friends, and gives them permission to access this class today. By using a friend relationship, a common function or a member function of a class can access data encapsulated with another class. To some extent, the relationship with friends is a breach of data concealment and encapsulation. *in a class, you can use the keyword friend to make other functions or class life friends. If a friend is a general function or a member function of a class, it is called a friend function; If a friend is a class, it is called a friend class, and all the functions of the friend class automatically become friend functions. * (1). A friend function is a non-member function that is decorated with a keyword friend in a class. A friend function can make a normal function or a member function of another class. * #include"iostream"#include"Cmath"using namespacestd;classpoint{ Public:P oint (intx=0,inty=0): X (x), Y (y) {};intGetX () {returnx;}intGetY () {returny;} FriendfloatDist (point &p1,point &p2);//friend function declaration;Private:intx, y;};//the definition of friend function DistfloatDist (Point &p1,point &p2) {Doublex=p1.x-p2.x;Doubley=p1.y-p2.y;returnstatic_cast<float> (sqrt (x*x+y*y));}intMain () {Point myP1 (1,1), MyP2 (4,3); cout<<"The distance is:"; cout<<dist (MYP1,MYP2) <<Endl;return 0;}*In the point class, only the prototype of the friend function is declared, the friend function dist is defined outside the class, and you can see that the friend function accesses the X and Y properties of the point class directly through the object name. ** (2). Friend class:*If Class A is a friend of Class B, all member functions of Class A are friend functions of Class B and can access private and protected members of Class B. *classb{* FriendclassA//Declare a friend Class B. * };*declaring a friend class is a way of building the practice between classes and classes to implement the sharing of data between classes and classes. * #include <iostream>using namespacestd;classa{ Public:voidDisplay () {cout<<x<<Endl;}intGetX () {returnx;} FriendclassB;Private:intx;};classb{ Public :void Set(inti);voiddisplay ();Private: A;};voidB::Set(inti) {a.x=i;//because B is a friend of a, all private members of Class A can be accessed in the member function of B;}**Note: Friend relationship is not transitive, B is a friend, C is a friend of B, if there is no declaration that C is a friend, there is no friend relationship. A friend relationship is one-way, and if B is a friend, B can access A's private data and protect the data, but A's member function cannot access B's private and protected data. A friend relationship cannot be inherited, and if B is a friend, the derived class of B cannot automatically become a friend of a. **5. Protection of shared data:* (1). Constant object:*The data member value of a constant object cannot be changed throughout the lifetime of the object. This means that the constant object must be initialized and cannot be updated. *ConstThe name of the type descriptor object;*classa{ Public: A (intIintj): X (i), Y (j) {};Private :intx, y;};ConstA A (3,4);//A is a constant object and cannot be updated. ** (2).Constdecorated class Members:*Common member functions: functions decorated with the Const keyword are constant member functions, declaring the format:* Type specifier function name (parameter table)Const;*If an object is set to a constant object, only its regular member function can be called through the regular object, and no other member function is called;* The Const keyword can be used to differentiate between overloaded functions,voidPrint ();voidPrint ()Const;*constant data member: A data member that uses the const description is a constant data member, and if a constant data member is described in a class, the constant data member cannot be assigned a value in any function. * #include <iostream>using namespacestd;classa{ Public: A (inti);voidprint ();Private:Const intA;Static Const intb;};Const inta::b=Ten;//static constant data members are described and initialized outside of the class;A::a (inti): A (i) {}//regular data members can only get the initial value by initializing the list;voidA::p rint () {cout<<a<<":"<<b<<Endl;}intMain () {A A ( -), A2 (3); A.print (); A2.print ();return 0;}**frequently cited:*If a const modifier is used when declaring a reference, the declared reference is a constant reference, and the object referenced by the regular reference cannot be updated. If a constant reference is a formal parameter, changes to the argument do not occur. *ConstType descriptor &reference name;*A non-const reference can only be bound to a normal object, not to a constant object, but a constant reference may be bound to a constant object. A constant reference, whether it is bound to a normal object or a constant object, when accessed by that reference, the object can only be treated as a constant object. This means that for a reference to a base data type, you cannot assign a value to the data, and for a reference to a class type, you cannot modify its data member or call its non-const member function. **6. C++Multi-file structure and compilation preprocessing commands:* (1). C++general structure of:* In multiple file structures, #include指令的作用是将指定的文件嵌入到当前源文件中, this embedded file can be used to make CPP files, or H files. The directive include is written in two ways: #include < file name > means searching for the file to be embedded in a standard way, which is located under the Include subdirectory of the compiler environment, typically in the same way that the standard files provided by the system are embedded. The other is # include"file name"indicates that the file to be embedded is searched in the current directory first, if it is not searched in the standard way. * (2). External variables:*external variables can be used in the source file, and can be used by other files. The variables defined in the namespace scope are external variables by default, but if you need to use this variable in other files, you need to declare it with the extern keyword. * (3). External functions:*functions declared outside of all classes (non-member functions) are namespace-scoped, and if there are no special instructions, such functions can be called in different compilation units as long as the invocation is preceded by a referential declaration. You can also use extern adornments when declaring a function prototype or defining a function. **7. Standard C + +Library:* The Library of C + + retains most of the C language system functions and other predefined templates and classes. Using standard C + +Library, you also need to include the following statement to introduce the names in the specified namespace into the current scope:*using namespacestd;* If you do not use the usingnamespaceSTD, you need to use an identifier in the Std namespace with the namespace name std::;* (1). Compile preprocessing:*#include指令:*The file contains the directive, which works by embedding another source file in the current source file at that point, usually using the # include directive to embed the header file. *#define和 #undef Instructions:* #define曾经在C程序中被广泛使用, but some of the features that # define can accomplish can be well replaced by some of the language features introduced by C + +. Define the symbolic constants in C by defining them in # #, such as:#definePI 3.14; Symbolic constants are also defined in C + +, but a better approach is to have a const adornment in a type description statement. #undef的作用是删除由 the macro defined by # define so that it no longer works. *conditional Compilation directives:*#ifConstant expression or #ifdef identifier or #ifndef identifier *procedure section;*#elif*procedure section;*#else*procedure section;*#endif* */

My C + + notes (sharing and protection of data)

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.