A demo Society C + + programming __ Programming

Source: Internet
Author: User
Tags class definition define function function definition mutex

This article contains the basics of C + +, starting not for 0 basic programmers. If you're just not so comprehensive about the knowledge of C + +, or if you've forgotten a part of the basics, then this article is perfect for you. If you have any questions, you can leave a message.

This demo mainly includes three files: Namespace.h file, including the custom space, space function, space variable, space custom class, namespace.c file for namespace.h file to define the implementation of functions, main.cpp file main program operation.

Namespace.h and namespace.cpp include the definition and implementation of custom base, inheriting class, and template class. Involves the constructor of the custom class, the overloaded constructor, the default value of the function, destructors, copy constructors, overloaded operators (Assignment functions, addition functions), virtual functions, literal functions, static functions, static variables, constant variables, enumeration variables, inner classes, access modifiers, inheritance, overriding virtual functions, base class references, Indefinite parameter function, friend function, friend class, type reference, final state function, final state class, template variable and so on.

Namespace.h file

#pragma once//prevent file from being multiple included #include <stdio.h> #include <iostream>//Data Flow #include <string>//String #includ e <exception>//exception #include <stdarg.h>//Variation Parameters #ifndef Pi///If no pi is defined, skip to avoid repetition including #define PI 3.1415926 #  endif using namespace std;                                 

Common space function//custom namespace namespace MyNamespace {//static integral type static long timenow;//Custom Function void Myfun (string str); Custom class-Student class Student {public://Common Member                                                      , externally accessible members Student ();                       The parameterless constructor//default constructor (parameter All-all default value + parameterless function) can call Student (string name,int age=default_age) without parameters;                                               The argument constructor//function name is the same, method overload, age contains default parameters, this parameter is optional Student (int age);                                                The parameter constructor//function name is the same, method overload, the function name is the same, the parameter type and quantity are different for the reload, and the return value is independent of the virtual ~student (); destructor//The function is called automatically when the object is destroyed, which is used to free memory, preferably as a virtual function, so that the Polymorphic property can destroy the memory created by the derived class object.Tudent (const student& another);                     Copy constructor student& operator= (const student& another);   Overloaded assignment operators, which generate class objects within functions, return classes without generating class objects, no return class references//can overload the relational operator arithmetic operator increment decrement operator bitwise operation two Yuan logical operator insert << operator extraction >> operator subscript operator                Function call operator dereference operator memory allocation and release operator Student operator+ (const student& another) const; Addition operator Overloaded Student addition operation, the const function does not change the members of the class, the returned object does not return the reference because a new object is generated, and there is a Student operator+ with the original object (const string&             anothername) const; The addition operator overload avoids implicit conversions when overloaded + must be behind the student.                              The object name can be returned as an object, and the virtual void SetName (string name) can be returned as an object reference;                                         Virtual keywords, virtual functions, support derived class overrides, preferably all functions are set to virtual functions, Java is the way to do string getname () const;                                           Functions that do not change data members are declared as const void Setage (int age);                                            general function Declaration static int getage (); Static keyword, static function, static method cannot override, no inheritance//static method belongs to the name of the class that defines it, does not belong to a particular object, and is called using the nameWord parsing static string default_name;                                static data, stored in the static zone, statically const int default_age=18;
                                                                    The const keyword, the constant value data, the data is stored in the literal constant area, and the const data definition needs to be assigned a value.                                          mutable the variable enum Allsex{boy,girl} with variable variables that can change the value in the Const function; Enum keyword, enumeration type, used to qualify the range of parameters, equal to define, or const class sex{//define inner class, sexual   
        Don't public:string getsex ();                                void Setsex (Allsex sextype);
    Use an enumeration type as a parameter private:string sexstr;
};
Protected://The member string name that the derived class can access;
Private://member int age that can only be accessed within a class;


};  Derived class-Class Monitor:public Student//Public inheritance the highest access rights for the base class the permissions for all operations are automatically demoted to this permission Try to use public {public: Monitor () {//constructor cannot inherit This->task = "Help teacher manage Class";
         The function definition can be implemented directly in the declaration, or it can be implemented in the object CPP or not implemented, and the Name= "monitor" is realized when the call is made.                           cout<< "parameterless derived class constructor" <<endl; cout<< <<endl;    
     Output to Dos window};
     virtual void SetName (string name) override//override, overriding virtual method virtual, override can not write, override write to confuse hidden functions                                           {this->name=name;
     This sets the name parameter as an object student cout<< "derived class:" +name<<endl;                                        Using Student::getname;                                 Contains a base class function that contains a method that contains all versions of the same name defined in the base class, with the Using keyword, which is equivalent to expanding string GetName (string surname) in the current
         Creates a new member function, which forms an overload with the base class because the arguments are different, and if you do not use a using containing, the base class function {cout<< derived class gets the name parameter: "+surname+name<<endl;
     return surname+name;           } void Setage ()                                       Hides the base class function with the same name as the base class function {age=7;
     cout<< "derived class setting Age parameter:" <<age<<endl; int Getage () {//Create object member function, function in base class is static function, not belong to object, belongs to class COUT&LT;&L t; "
         Derived class Read age parameter: <<age<<endl;
     return age;
     };                                String Gettask () {return task;}; Create an object member function void Settask (string task,...) {                                 //... Represents an indefinite number of parameters.                                           Create an object member function va_list arg_ptr;                                    Define the parameter list va_start (Arg_ptr,task);
        Binds the start position of the argument list to the first argument string aa= "";
             while (aa!= "&&!aa==null)//cannot judge the number or end of a parameter list, you must pass in the attribute parameter to represent the number or the end of {                           AA = Va_arg (arg_ptr,string);                                           Iterate over the read parameters and convert them to the corresponding type} va_end (ARG_PTR);
     Parameter cleanup work    This->task = task;                 
 };                                                       Private:int age;                                                   The age in the base class is private, the derived class is inaccessible, and the derived class redefine the string task;





 Add derived class own properties}; Custom class-Teacher class Teacher {public:teacher (): Name ("Teacher"), Course ("language") {//base class default constructor, and initial
     data member name, Course cout<< "base class parameterless constructor:" +name<<endl; 
     };   Teacher (string name) {cout<< "base class has a parameter constructor:" +name<<endl;};                        A parameter constructor for a base class ~teacher () {cout<< "base class destructor" <<endl;};                                          destructor friend class Student;                     Friends, all methods in the Student class can access teacher private, protected, public data members, and method friend void Student::setname (string name);                               Only functions that set friends can access members and methods of the current class, and only the Student:;setname function can access teacher member methods Virtual student& getstudent () = 0; = 0 Represents a pure virtual function, no method is defined, only a method is declared, a class containing pure virtual functions is an abstract class, and an abstract class cannot be an instance object
     virtual void Setstudent (student& students) = 0; 
         & As a reference, equivalent to the variable alias virtual string getname () final{//final function, which prohibits rewriting, and is overridden when a derived class is inherited again;  
     cout<< "base class gets the name parameter:" +name<<endl;return name; 
 virtual void SetName (string name= "Teacher") {this->name = name;};                    Private:virtual string GetCourse () {return course;};
 In C + +, private functions can also be virtualized overrides, which can be modified by the access limiter string name only when the public and protect methods are overridden in Java;
 Protected:string course;



 };                                      Create Class class headmaster Final:public Teacher//final tag classes cannot be inherited {public://using teacher::teacher; Constructor cannot inherit, only call Headmaster () {cout<< "derived class parameterless constructor: Headmaster" <<endl;}; The default constructor headmaster (string name) of the base class is called automatically before the constructor call of the derived class: Teacher (name) {//The constructor of the derived class, which invokes the base class of the display reference before calling
     Constructor cout<< "Derived class has a parameter constructor:" +name<<endl;  
     }; ~headmaster () {cout<< "derived class"destructor <<endl;};     When destructors//use, the default parameter values are override according to the pointer type function method according to the//virtual void SetName (String name= "headmaster") of the Pointing object; When the constructor of a derived class has no using, the default is to write all versions with a using, which means that the current version of the derived class is overridden by using different default parameters virtual student& getstudent () Override{retu       RN student;}; Remember to add override because the base class changes and the derived class does not change the error, so the reminder modifies the derived class virtual void setstudent (student& students) override{//should be rewritten, heavy Load method, all versions. 
     Virtual functions can not be overridden, overriding does not override all to keep the function of the virtual property this->student = student;           Virtual string GetCourse () Override{return course; 

 Overrides the private function of the base class and modifies the access modifier private:student Student;

 };


 }; Template<class tt=int> class classa{//template<class t> is a template, type T is an indeterminate type, and ClassA is a class modulo                                           Board, you can set a default value for an indeterminate type, but you still need to use the <> public:tt Add (TT tt,tt pp) when using the class definition example;
     Use the template function to Template<class tt> TT plus (TT tt,tt PP) {//To define the function return TT+PP within the class template; }
 };

 

Custom space Namespace.app files

#pragma once//prevent file from being multiple included #include <stdio.h> #include <iostream>//Data Flow #include <string>//String #includ
E "namespace.h" using namespace std;
using namespace MyNamespace; void Mynamespace::myfun (String str) {cout<<str<<endl;}//constructor//Set member data Initialization value Student::student (): Name ("Stu 
    Dent "), age (Default_age) {cout<< non-parametric base class constructor: ' +name<<endl;}//Constructor Student::student (String Name,int age) {
    this->name=name;
    This->age = age;
cout<< "There is a parameter base class constructor:" +name<<endl;
    }//constructor student::student (int age) {this->age = age;
    Name= "Student";
cout<< "There is a parameter base class constructor:" +name<<endl;
    }//Copy constructor student::student (const student& another) {name=another.name;
    Age=another.age;
cout<< "base class copy constructor:" +name<<endl;
        }///Assignment Constructor student& student::operator= (const student& another) {//Self assignment Detection if (this==&another) {
    return *this; //Release this original memory//assign new memory name = Another.name;
    Age=another.age;
    cout<< "base class assignment constructor:" +name<<endl;
return *this;
    }//Operator overload Student student::operator+ (const student& another) const {Student Student;
    Student.setname (name+ "and" +another.name+ "' s Group");
    Student.setage ((age+another.age)/2);
    cout<< "base class addition operator overload" <<endl;
return student;
    }//Operator overload Student student::operator+ (const string& anothername) Const {Student parents (anothername);
    cout<< "base class plus string operator overload" <<endl;   return parents;  You cannot return a reference to a local object. Returns the object, assigns the local object to the receiving object, and then destroys the local object. Do not destroy the pointer memory.
Returns a reference, assigns a local reference to a receive reference, and then destroys the local object, and the content that receives the reference is destroyed.   } void Student::setname (string name)//No need to reuse virtual {this->name=name;
This is the object student cout<< "base class set name parameter:" +name<<endl;}
    String Student::getname () const {cout<< "base class reads the name parameter:" +name<<endl;  Return (*this). Name;
This is the pointer that can be used to point to the value//return name;
    } void Student::setage (int age) {cout<< "base class setting aging Parameters" <<endl;
this->age=age; }
int Student::getage () {cout<< "base class shared static function read Age parameter" <<endl;   return default_age; Static functions can only manipulate static data}//destructors so the stack pointer always automatically releases the memory from the point in the heap when the function exits.
    Cause original Memory corruption (call function) Student::~student () {cout<< "base class destructor:" +name<<endl; Here, fill in the function to free object memory}//nested class function definition string Student::sex::getsex () {return SEXSTR}//nested class function defines void Student::sex::setsex (alls
    Ex Sextype) {if (sextype==boy) sexstr = "Boy";
else Sexstr = "Girl"; The method of defining member functions outside the class template is to:template< template parameter list > function return type class name < template parameter name:: Function name (parameter list) {function body}, Template<class tt> TT               



 Classa<tt>::add (TT Tt,tt pp) {return tt+pp;}

The main.cpp file mainly involves header file references, space reference, struct, type alias, constant value variable, global variable, constant value function, function alias, function pointer, function declaration, function parameter, inline function, template function, time function, input output stream, string conversion, variable derivation, pointer and array of class, Lambda expressions, smart pointers, type-up transitions, input and output file streams, STL containers and algorithm operations, arrays, vectors, lists, stacks, queues, sets, mappings, iterators, search algorithms, partitioning algorithms, sorting algorithms, Operation algorithms, string regular expressions, multithreading, thread safety, custom literal , variable-length templates and other content

Main file Main.cpp file

#pragma once//prevent file from being multiple included #include <stdio.h> #include <stdlib.h> #include <chrono> Regular expression vs2012 #include <iostream>//Data Flow #include <memory>//memory operation #include &L t;fstream>//File stream #include <string>//String #include <regex>//Regular expression #incl Ude <exception>//exception #include <stdexcept>//exception type #include <iterator>//Iterator # Include <array>//available fixed-size fixed array #include <vector>//data structure continuous distribution of dynamic array #include <list&gt               ; Discontinuous distributed two-way list #include <deque>//bi-head queue #include <queue>//First-in-first out queue #include <stack&gt              ;          First in and out heap #include <set>//ordered set #include <map>//hash table #include <algorithm> STL algorithm #include <numeric>//numerical calculation algorithm #include <math.h>//numerical calculation algorithm #include <functional>//function pointer, the function pointer as a custom function parameter implementation set callback function #include <thread>//multi-line threading vs2012 after the #include <atomic>//Atomic type thread-safe vs2012 after #include <mutex>//Mutex type vs2012 there is #include <time. H>//Time type #include "namespace.h"/Custom Space "" First search local directory and then traverse all <> Traverse System directory reference h file equivalent to H file directly expand us                                                    ing namespace std;                                            Reuse space functions using namespace MyNamespace; Custom namespaces to avoid conflicting variable functions with the same name in different spaces struct people//custom struct {Strin
    G name;
int age;                                                               }people1;                                                    People is a type, PEOPLE1 is a variable typedef int* IntPtr;                                   The Type alias typedef provides a new name for an existing type declaration using a similar function const string studentname = "Student";   Constant variables any no longer namespace, functions, names in the class are considered global action string stringtemp= "";                                                global variable const int Getstudentnumber () {return 33;}                                        Constant-expression typedef void (*funtype) (string); Define function pointer type input string return void equivalent to using Funtype = void (*) (string);.                In order to appear the high frequency code, avoids the change tedious and the writing tedious//function<void (string) > Function_pointer = printstring;                    function pointer//void (*function_pointer) (string str) = printstring;                                           function pointer void printstring (string str);     function declares void process (const vector<string>& vec,function<void (String) > Fun); function declares a inline void Sprintf1 (string str) {//inline function, which is expanded at compile time at the code, for a function with a high frequency for reading and a small amount of code.
Avoid cumbersome types and invoke shortcut cout<<str<<endl; } void Printstring (String str)//Custom Function (print output string) {cout<<str<<en
dl } void Process (const vector<string>& vec,function<void (String) > FUN//Custom Function (call function fun, call vector member) {for (auto& Item:vec) fun (item);} template<class t> void print (T a)//template function, function template formula {cout<<a<<endl;} string Student::d Efault_name = s                             Tudentname;                                          A static variable within a class without creating an object, initialization needs to be placed outside of the function global area int main () {myfun ("Code debugger: Shangpeng");                   Call the custom space function,//Two string constants cannot be added cout<< "============ basic type Data ============" <<endl;                                               cout<< <<endl Print Output TimeNow = time (NULL); Space static variable, used directly, this sentence returns only a timestamp cout<< "current timestamp" <<timenow<< "\ n";

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.