C + + Common syntax

Source: Internet
Author: User
Tags function definition function prototype int size logical operators
C + + files

Example: from a file income. Read the revenue until the end of the file,
And output revenue and taxes to file tax. Out

#include <iostream>
using namespace std;
const int cutoff = 6000;
const FLOAT RATE1 = 0.3;
Const float RATE2 = 0.6;
int main ()
{
  ifstream infile;
  Ofstream outfile;
  int income,tax;
  Infile.open ("income.in")
  outfile.open ("Tax.out") while
  (infile>>income) {
    if (income< Cutoff)
      tax = rate1 * income;
    else
      tax = rate2 * income;
    outfile<< "income =" << income
              << "greenbacks\n"
              << "Tax =" << Tax
              < < "greenbacks\n";
    }
    Infile.close ();
    Outfile.close ();
    return 0;
}

Check that the file is open successfully

Ifstream infile;
Infile.open ("Scores.dat")
if (infile)
  //...
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main ()
{
    ifstream infile;
    Ofstream outfile;
    Infile.open ("In.txt");
    Outfile.open ("OUT.txt");
    int num1,num2,num3=0;
    if (infile && outfile)
    {while

        (infile >> num1 >> num2 >> num3) {
            outfile < < SETW (2) << num1<< "" <<num2<< "" <<num3<< "" <<num1+num2+num3<< Endl
        }
    }
    Infile.close ();
    Outfile.close ();
    return 0;
}
Constants

The const variable in C + + can be used where any constant can occur, such as the size of the array, the expression in the case label.

const int Size = m;
float A[size];
BOOL Data Type

C + + new bool type, value TRUE or false. Used to indicate true or false.
All relational operators, equality operators, and logical operators are now
Produces the result value of type bool, not the INT type.
Where the type of bool is needed, the integer and pointer expressions are still acceptable
Xu's
By default, the BOOL expression outputs a true value of 1, and a false output of 0.
The operator Boolalpha can be used to output or enter a bool expression in the form of false or true.
The operator Noboolalpha can be used to output a bool expression or enter a 0 or 1 form.

BOOL Flag;
Flag = (3<5);
cout<<flag<< ' \ n ';
cout<<boolalpha<<flag<< ' \ n ';

1
True
Structure

The structure in C + + is different from the C language structure. You can define a struct variable without struct the keyword

struct point{
  double x,y;
Point P1,p2;

A struct in C + + can contain functions in addition to data members.

struct point{
  double x,y;
  void Setval (double,double);
};
p.x = 3.14159;
p.y = 0.0;
P.setval (4.11,-13.090);

In C + +, the only difference between classes and structs is that everything in the structure is public by default, and everything in the class is private. String Type

C + + provides a string type to override a null-terminated char array in the C language.
Use string type must include header file string
With the string type, programmers no longer need to care about the allocation of storage or to handle complex null-ending characters, which are handled automatically by the system.
Instance:

#include <string>
using namespace std;
string S1;
String s2= "Bravo";
string s3=s2;
String S4 (' X ');

Variable s1, defined but not initialized, default value is empty string
The initial value of the variable s2 is the C-style string "Bravo"
Variable s3 are initialized with S2, so both S2 and S3 represent string Bravo
The S4 of the variable is initialized to 10 x.

Convert to C-style string: Use function C_str to return a pointer to an array of type Char

Instance:
The data type of the variable filename that holds the input file name is string
When calling the Ifstream open function, you need a C-style string

string filename = "Infile.dat";
Ifstream infile;
Infile.open (Filename.c_str ());

To find the length of the string, use the function length

string s = "Ed Wood";
cout << "Length =" << s.length () << ' \ n ';

The output is length = 7.

The input and output of string
<< to output string of type string

string S1;
String s2 = "Bravo";
string s3 = S2;
String S4 (' x ');
cout<<s1<< ' \ n '
       <<s2<< '
       <<s3<< ' <<s4<< '
       \ n ';

Output for

Bravo
Bravo
xxxxxxxxxx

Used to enter a string of string whose default action is to ignore spaces and then read the stored characters until the file ends or another space is encountered. No spaces are stored.

string S;
cout << "Enter a string:";
CIN >>s;
Input
Ed Wood

The content of S is ed.
Note: After the definition, s actually has a length of 0. After reading the string Ed, it has a length of 2. The system automatically provides sufficient storage space to store this length 2 string.

function Getline: Used to read a whole line into a variable of type string. The first argument is the input stream, and the second parameter is a variable of type string.

The function reads characters from the input stream and stores them in a string variable until the following occurs:
Read the file end flag.
To a new row, which is removed from the stream but not stored in the variable.
The maximum length allowed value to reach the string.
If Getline does not read the character, it returns false, which can be used to determine whether the file ends to terminate the application

Instance:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
    string buff;
    Ifstream infile;
    Ofstream outfile;
    cout<< "Input file name:";
    cin>>buff;
    Infile.open (Buff.c_str ());
    cout<< "Output file name:";
    cin>>buff;
    Outfile.open (Buff.c_str ());
    while (Getline (Infile,buff))
        outfile<<buff<< "\ n";
    Infile.close ();
    Outfile.close ();
    return 0;
}

The line spacing of the output information is twice times the input information spacing.

Assignment: operator = An assignment that can be used to string strings of string type
The left side of the operator must be a string of type string, and the right can be a string string, or it can be a C-style string or just a char character.
Concatenation of strings: operator + and + = can be used to concatenate strings.
operator +
String + string
string + "xxxxx" or "xxxxx" + string
string + ' x ' or ' x ' + string
and = =, the left must be a string, and the right can be a
String, C-style, or a char character.
–string + = string
–string = "xxxx"
–string + = ' x '

Function
Application: Marked by &, used to provide aliases for memory

int x;
int &ref = x;
An int unit is assigned, it has two names: X and ref
x=3; or ref=3, all of which save 3 to the INT unit

C + + The default invocation method is the same as the C language, is a value call. If you specify a function argument as a reference parameter with &, the reference argument calls the actual argument to the function instead of a copy of the argument.

#include <iostream>
using namespace std;
void swap (int &,int &);
int main ()
{
  int i=7,j=-3;
  Swap (I,J);
  cout<< "i=" <<i<< ' \ n '
         << "j=" <<j<< ' \ n ';
  return 0;
}
void swap (int &a,int &b)
{
  int t;
  t = A;
  A = b;
  b = t;
}

function prototype void swap (int &,int &) specifies that the parameters of swap are passed by reference.
After swap is invoked, A and B in the swap function body directly correspond to the storage space of I and j in the main function. The function swap does not operate on the copy of the I,J, but directly operates the I and J itself.

Function Overload: The function name is the same, the number of parameters or parameter type is different.
Overloaded functions are often used to provide a generic name for operations that have similar behavior and have different data types. The compiler determines which function should be called by matching the argument type with the parameter table of the function with the same name.

#include <iostream>
#include <iomanip>
using namespace std;
void print (int a);
void print (double a);
int main ()
{
  int x = 8;
  Double y = 8;
  print (x);
  print (y);
  return 0;
}

void print (int a) {
  cout<<a<< ' \ n ';
}
void print (double a)
{
  cout<<showpoint<<a<< ' \ n ';
}

Function Signature: C + + requires overloaded functions to have different signatures.
The function signature includes: function name. The number of parameters, the type and order of the data.
To ensure the uniqueness of a function, a function must have a unique signature.
The return value type is not part of the function signature, so the function cannot be distinguished by the return value type. new and delete operators

The new new[] Delete and delete[] operators are used to dynamically allocate and free storage space (for example, when a program is running)
operator new allocates a space;
New[] allocates an array;
Delete Frees a single space allocated by new;
Delete[] Releases an array allocated by the new[];
Unlike functions in C, malloc calloc and free
The new, new[] Delete delete[is a built-in operator, and malloc calloc free is a library function. New and delete are keywords

The new operator infers the return type and the number of bytes to allocate based on the type of the request assignment.
Given declaration

int *int_ptr;

Storage space is usually allocated for INT_PTR using the following methods;
INT_PTR = new int;
If the assignment succeeds, the INT_PTR points to the allocated storage unit.
The delete operator is used to free the storage space allocated by new. If int_ptr points to a single int cell that is assigned by new, you can release it like this

Delete int_ptr;

New[] operator is used to dynamically allocate an array

int *int_ptr;
INT_PTR = new int[100];//request allocates 100 int type units

If the assignment succeeds, INT_PTR points to the address of the first int unit

The delete[] operator is used to free the storage space allocated by new[. If int_ptr points to an array of int that is allocated by new[], then we can release it like this:

delete [] INT_PTR;
class

In C + +, a class is a data type.
Standard C + + defines some built-in classes, such as String
By creating your own classes, programmers can extend the C + + language.
A class declaration enables you to create a class, and you can use it as a data type.

Classes and objects
Class declaration: Describes the data members and member functions encapsulated in the class.

Class human{
       ///...data members and methods go here
};

Class is a keyword, human is called a class label
A data type is created by the class declaration, which is the identifier or name of the data type.
The semicolon after the curly braces in the class declaration is not limited.
Object definition: From an object-oriented programming perspective, a variable defined as a data type in C + + is an object.
Human maryleakey;//The following statement defines an object for Human Maryleakey
Object array Human latvians[365000];
The information hiding mechanism of C + +
Three keywords:
Private: Can be used to hide data members and member functions of a class
Public: Used to expose the data members and member functions of a class
Protected

The soul of object-oriented design is to use the implementation of private hidden classes, using the interface of public exposure classes.
Define a person class
Interface: contains two public member functions Setage and Getage
Implementation: A unsigned type of data member age

Class person{public
  :
    void Setage (unsigned n);
    unsigned getage () const;
  Private:
    unsigned age;

Private members and public members can cross in the class declaration.
The client of the person class (the consumer of the object of the person Class) can request a person class to provide a service by invoking the public member function setage and Getage
Clients of the person class cannot access private data member Age that belongs to the class implementation section
Member Selector

Class person{public
  :
    void Setage (unsigned n);
    unsigned getage () const;
  Private:
    unsigned age;
int main ()
{person
  boxer;
  Boxer.setage (a);
  ... remainder of main ' s body

Object can only access public members of the class (data members or member functions)
Class scope
A private member of a class can only be accessed by a member function of a class, that is, a class-scoped property.
A public member of a class has a public-domain nature that can be accessed outside the class.
In C + +, classes declared with the keyword class, whose class members are handled by default as private members, have a class-wide nature.
The difference between keyword class and struct
Classes can be created using either the class keyword or the struct keyword
If you use the Class keyword, class members are private in the default state.
Instead, the struct keyword is used, and class members are publicly owned in the default state. class member function definition

Defined outside a class declaration, defined in a class declaration (inline)

Class person{public
:
    void Setage (unsigned n);
    unsigned getage () const;
Private:
    unsigned age;

Define person ' s setage
void person::setage (unsigned n) {age
    = n;
}
Define person ' s getage
unsigned person::getage () const{return age
    ;
}

Defined outside the class declaration, in order to avoid the duplicate name, a domain parser is used when defining a member function::

Defined within a class declaration (inline)

Class person{public
:
    void Setage (unsigned n) {age = n;}
    unsigned getage () Const{return age;
Private:
    unsigned age;

By using the inline keyword when declaring a member function, you can force a member function that was originally defined outside the class declaration to be an inline function.

Class person{public
:
    inline void setage (unsigned n);
    inline unsigned getage () const;
Private:
    unsigned age;

Define person ' s setage
void person::setage (unsigned n) {age
    = n;
}
Define person ' s getage
unsigned person::getage () const{return age
    ;
}

Using classes in programs
Key steps: class declaration, object definition, customer service request

#include <iostream>
using namespace std;

Class person{public

:
    void Setage (unsigned n) {age = n;}
    unsigned getage () const{return age;}

Private:
    unsigned age;

int main ()
{person
    p;  Create a
    stooges[3];//create an array of Persons
    p.setage (a)
    ; Set the Stooges ' Age
    Stooges[0].setage ();
    Stooges[1].setage (+);
    Stooges[2].setage (a);
    Print four ages

    cout<<p.getage () << ' \ n ';
    for (int i=0;i<3;i++)
        cout << stooges[i].getage () << ' \ n ';
    return 0;
}

Using classes in programs
Class declarations are typically placed in. h, so that class declarations are included through #include when used.
If you can place the declaration of the person class in the Person.h file
Typically, the definition of a member function is placed in. cpp
In general, do not place member function definitions in. h Because header files can be #include by multiple different files. function Duplicate definition error may occur

Instance program: Stack class
Problem: Create a stack class that supports push and eject operations of int type.
Public Member:
initializes the Stack object. The
checks that the stack is empty or full. The
presses the integer into the stack. The
pops up an integer from the stack. The
does not move any elements, outputting the contents of the stack to standard output.
Private member:
A private member function that prints the error message.
Three private data members (top, data array, dummy_val)

#include <iostream> using namespace std;
    Class stack{public:enum{maxstack = 5};
    void Init () {top =-1;} void push (int n) {if (Isfull ()) {errmsg ("full stack.")
            Can ' t push. ");
        Return
    } Arr[++top] = n; int pop () {if (IsEmpty ()) {errmsg ("Empty stack.)
            Popping dummy value. ");
        return dummy_val;
    return arr[top--];
    BOOL IsEmpty () {return top<0;}
    BOOL Isfull () {return top>=maxstack-1;}
        void dump () {cout<< "Stack contents, top to bottom:\n";
    for (int i=top;i>=0;i--) cout<< ' \ t ' <<arr[i]<< ' \ n '; } private:void errmsg (const char* msg) const{cerr<< "\n*** Stack operation failure:" &LT;&LT;MSG&LT;&L t; '
    \ n ';
    int top;
    int Arr[maxstack];
int dummy_val;

};
    int main () {Stack S1;
    S1.init ();
    S1.push (9);
    S1.push (4); S1.dump (); 4 9 cout<< "Popping" <<s1.pop () << ' \ n '; S1.dump ();
    9 S1.push (8); S1.dump ();
    8 9 S1.pop (); S1.pop (); S1.dump ();//empty S1.pop ();//still empty s1.dump ();
    Ditto S1.push (3);
    S1.push (5);
    S1.dump ();//5 3//push two too Manny to test for (unsigned i = 0;i<stack::maxstack;i++) S1.push (1); S1.dump ();
1 1 1 5 3 return 0; }

Efficiency and robustness
-Passing and returning objects by reference
-object reference to the const type parameter
-Const member function
-Overload member functions to handle two types of strings

Passing and returning objects by reference
objects can be passed and returned by way of value or by reference. In general, you should use the reference method to carry out and return objects, rather than using the method of passing values. Because passing and returning objects by way of value reduces efficiency and faces copying between objects, making the data larger and wasting memory.
In terms of efficiency, passing a pointer to an object can receive the same effect as a reference, but the syntax of the reference method is much more concise.

#include <iostream>
using namespace std;

Class c{public
: 
    void Set (int n) {num = n;}
    int get () Const{return num;}

Private:
    int num;
};

void f (c&);
c& g ();

int main ()
{
    C c1,c2;
    F (C1); Pass by reference
    C2 = g (),//return by reference
    cout<< c2.get () << ' \ n ';
    return 0;
}

void f (c& C) {
    c.set ( -999);
    Cout<<c.get () << ' \ n ';
}

c& g () {
    static C c3;//nb:static, not auto
    c3.set (123);
    return c3;
}

Output:
-999

Object reference to the const type parameter
In general, if an object is passed to function f by reference, while function f does not change the state of the object by modifying the value of the data member of the object, it is best to mark the parameters of F as const, to prevent misinterpretation of the parameters, and some compilers can optimize the situation.
The following example: marking the function setname String type parameter n as const indicates that setname does not change n, but assigns N to data member name.

Class c{public
:
    void SetName (const string& N) {name = n;}
    . Other public members
private:
    string name;

Const member function
If a member function does not need to change any data member of the object that the function belongs to directly or indirectly (by invoking other member functions to change its object state), it is best to mark this member function as Const.
The following example marks a GET member function as const because the Get member function does not need to change any of the data members of Class C.

Class c{public
:
    void Set (int n) {num = n;}
    int get () const {return num;}
Private:
    int num;
};

Const member function
When you define a const member function, the const keyword appears between the argument list and its function body.
Because a GET member function does not change any data member, this type of function is called a read-only function. Marking a member function as const prevents misinterpretation of the data members of the object to which the function belongs, while some compilers can also optimize the situation.
A const member function can invoke only other const member functions, because the const member function does not allow the state of the object to be changed directly or indirectly, while calling a non-const member function may indirectly alter the state of the object

Class c{public
:
    void M1 (int x) const{
        m2 (x),//*** error:m2 not const
    }
    void m2 (int x) {dm = x;}
private:
    int dm;

Const member function
const keyword Three different usage examples:
-In member function set, because set should not be variable string type parameter n,n is marked as const.
-member function Get returns a const reference to data member name, where the const indicates that no one can modify the value of the data member name through this reference.
-The member function get itself is marked as const because getting does not change the value of the unique data member name of Class C.

Class c{public
:
    void Set (const string& N) {name = n;}
    Const string& Get () const{return name;
Private:
    string name;

Const return
-If a function returns with a const, its return value can only be assigned to a const-type local variable.
-If the const return value is a pointer or reference to a class, then the Non-const member function of the class cannot be invoked with that pointer or reference, because these functions may change the value of the data member of the class.

class foo{public:/* Modifies M_widget and the user may modify the reurned widget.
    * * Widget *widget ();
     * * Does not modify m_widget but the user may modify the returned widget.

    * * Widget *widget () const;
    * * Modifies M_widget, but the user may not modify the returned widget.

    * * Const Widget *cwidget ();
    * * Does not modify m_widget and the user may not modify the returned widget.

* * Const WIDGET *cwidget () const;
Private:widget *m_widget;

};
    int main () {Foo F; Widget *W1 = F.widge 

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.