catalogue
1, The difference between C language and C + +
1. Transplantation of C standard library
2.C + + standard input / output stream
4, Difference between functions
7, Student achievement analysis
11, string type and destructor
12, Derivation, inheritance, virtual function
preface
C language wants to transition to C + +. I don't want to learn again, but I don't want to swallow it. This is my study note
1, The difference between C language and C + +
C + + language is the extension and enhancement of C language. It has changed from process oriented programming to object-oriented and general algorithm (generic programming)
Since C + + is an extension of C language, C language programs are also c + + programs. The original. C programs can be compiled and run on. cpp files.
2, Input and output
1. Transplantation of C standard library
There are many portable versions of C + + Standard Libraries in C + + Standard Libraries:
Header file:
The header file xxx.h of C standard library basically becomes cxxx As shown below:
//C language header file #Include < stdio. H > / * standard I / O stream function*/ #include<string.h> #include<math.h> //C + + header file #include<cstdio> #include<cstring> #include<cmath> //The exception malloc does not change #include<malloc.h>
Take a look at some simple examples:
It can be seen that some functions and operations suitable for C language are still feasible in C + +.
2.C + + standard input / output stream
Header files: iostream Contains C + + standard input / output stream functions
#include<iostream>
Output stream function: cout
Input stream function: cin
Input / output operators:<< or >>
O < < x, adding o is an object, X is data, O < < x means inputting the data of X into object o, and then returning object o
Take an example:
In order to prevent name conflicts, C + + language has a namespace. When using some names, you need to label the namespace, while cout and cin are in the namespace std. therefore, you must declare this namespace when using it. Generally speaking, there are three labeling methods. The method is as follows:
The first method:
#include<iostream> using namespace std;//The first method refers to all the in this namespace before use int main() { cout << "hallo world\n"; cout << 2 + 3 << endl;//endl means line feed, which is quite useful \ n return 0; }
The second method:
#include<iostream> using std::cout; //The second method is to annotate before use: use cout in std namespace using std::endl: //The second method uses endl in the std namespace int main() { cout << "hallo world\n"; cout << 2 + 3 << endl;//endl means line feed, which is quite useful \ n return 0; }
The third method:
#include<iostream> int main() { std::cout << "hallo world\n";//The third method: indicate the source before use. The format is std: std::cout << 2 + 3 << std::endl;//Label each use return 0; }
Examples of input and output:
3, Reference variable
In fact, the reference variable is the alias of the original variable,
The address is the same as that of the original variable
void SWAP(int a, int b) { int c = a; a = b; b = c; cout << &a << endl; } void SWAP2(int& x, int& y) { int c = x; x = y; y = c; cout<< &x << endl; }
int main() { int a = 1, b = 5; cout << a << '\t' << b << endl; cout << &a << endl; SWAP(a, b); cout << a << '\t' << b << endl; SWAP2(a, b); cout << a << '\t' << b << '\n'; return 0;
4, Difference between functions
Default parameter
function overloading
The following call method is wrong
Function template
5, User defined type
string type
vector class template:
#include<iostream> #include<vector> using namespace std; int main() { //vector // Vector is a vector, similar to an array, but can grow dynamically // vector is a class template. Instantiation generates a class // For example, vector < int > generates a vector < int > class (vector) whose data type is int // Similarly, you can access its members according to vector < int > class objects, such as member functions // Operators can also be used for operations // vector<int> k; k = { 1,2,3,4,5 }; k.pop_back();//pop_back() deletes an element at the end k.push_back(6);//push_back() adds an element at the end for (size_t i = 0; i < k.size(); i++) { cout << k[i] << '-'; } cout << endl; // Similarly, there are the following functions // clear() / / clear all elements // empty() / / judge whether the vector is empty. If true is returned, it is empty // erase() / / delete the specified element k.erase(k.begin() + 1); for (size_t i = 0; i < k.size(); i++) { cout << k[i] << '-'; } cout << endl; k.resize(3);//resize redefines the size of k for (size_t i = 0; i < k.size(); i++) { cout << k[i] << '-'; } cout << endl; k.clear(); if (k.empty()) return 0; for (size_t i = 0; i < k.size(); i++) { cout << k[i] << '-'; } return 0; }
Iterator iterator
int main() { //Iterator is an iterator in C + + vector<int> k = { 1,2,3,4,5, }; vector<int>::iterator it;//Here, create a variable it to iterate for (it = k.begin(); it != k.end(); it++) { cout << *it << ' '; } cout << endl; for (it = k.begin(); it != k.end(); ) { if (*it % 2 == 0) { it = k.erase(it);//After deleting 2, it points to 3 //After deletion, the position of the next element is returned } else it++; } cout << endl; k = { 0,1,2,3,4,5,6,7,8,9, }; it = k.begin() + 2; vector<int>::iterator it2 = k.end(); k.erase(it, it2); for (it = k.begin(); it != k.end(); it++) { cout << *it << ' '; } return 0; }
6, Dynamic memory allocation
int main() { //Dynamic memory allocation //New is used to apply for a new memory block, and delete is used to free it //For arrays, use delete [] int* p = new int[4]; for (size_t i = 0; i < 4; i++)//initialization p[i] = i; for (size_t i = 0; i < 4; i++)//Traversal output cout << p[i] << '\t'; cout << endl; char* s = (char*)p; char ch = 'A'; int n2 = 4 * (sizeof(int) / sizeof(char)); for (int i = 0; i < n2; i++)//initialization s[i] = ch + i; for(int i = 0; i < n2; i++)//Traversal output cout << s[i] << ' '; cout << endl; delete[] s; return 0; }
7, Student achievement analysis
struct student { string name; double score; void print();//Function declaration }; void student::print() //Note that the function implementation is outside the structure, and the namespace should be marked { cout << name << ' ' << score << endl; } int main() { vector<student> st; while (1) { student stu; cout << "Please enter your name and grade" << endl; cin >> stu.name >> stu.score; if (stu.score < 0) break; st.push_back(stu); } for (size_t n = 0; n < st.size(); n++) {//Traverse to view the input data st[n].print(); } //vector<student>::iterator it; //it = st.begin(); //it->print(); //The maximum, minimum, and average are output below int max = 0; int min = 0; double average = 0; for (size_t n = 0; n < st.size(); n++) { average += st[n].score; if (st[max].score < st[n].score) max = n; if (st[min].score > st[n].score) min = n; } st[max].print(); st[min].print(); cout << average / st.size() << endl; return 0; }
Insert a message this pointer
struct student { string name; double score; void print() { cout << name << '\t' << score << endl; } //this pointer //A this pointer is implied inside the member function //Actually void print() { cout <<this->name << '\t' <<this->score << endl; } };
8, class explanation
Basic application
//The difference between class and struct //Members inside struct are public by default //class members are private by default class student { private: string name; double score; public: void print() { cout << name << '\t' << score << endl; } //How do I access it externally? string get_name() { return name; } double get_score() { return score; } //How to modify externally? void set_name(string s) { name = s; } void set_score(double s) { score = s; } }; int main() { student std; std.set_name("Li Hua"); std.set_score(98.7); cout << std.get_name() << '\t' << std.get_score() << endl; std.print(); return 0; }
9, Default constructor
There is a default constructor inside the class structure type
class student { string name; double score; public: student(){};//The default constructor takes no formal parameters student(string n, double s)//This is not the default constructor { name = n; score = s; } } int main() { student stu;//When defining variables, call the default constructor. student stus[4];//When defining an array, there will be an error if there is no default constructor return 0; }
10, Operator overloading
Operator overloading
Input and output<< >> Operators can only be overloaded outside class
Subscript operator [] can only be implemented internally
Addition, subtraction, multiplication and division can be external and internal, but the implementation methods are different
// Operator overloading // The input / output < > > operator can only be overloaded outside class // Subscript operator [] can only be implemented internally // Addition, subtraction, multiplication and division can be external and internal, but the implementation methods are different class point { double x, y; public: point() {};//This is the default constructor //Internal implementation of addition operator point operator+(const point q) { return point(this->x + q[0], this->y + q[1]); } //Subscript operator overload (output only) double operator[](int i) const{ if (i == 1) return y; else if (i == 0) return x; else throw "Illegal subscript\n"; } //Subscript operator overload (can be output or modified) double& operator[](int i) { if (i == 1) return y; else if (i == 0) return x; else throw "Illegal subscript\n"; } //Its own constructor, used to initialize point(double x1, double y1)//This is not the default constructor { x = x1; y = y1; } //friend function friend ostream& operator<<(ostream& o, point s); friend istream& operator>>(istream& in, point& s); }; //Operator < < overload ostream& operator<<(ostream& o, point s) { cout << s.x << '-' << s.y << endl; return o; } //Operator > > overload istream& operator>>(istream& in, point& s) { cin >> s.x >> s.y; return in; } #if 0 //External definition of addition operator point operator+(const point p, const point q) { return point((p[0] + q[0]), (q[1] + p[1])); } #endif int main() { //Use of common subscript operators point p(2, 3); point pp[3] = { {1,1},{2,2,},{3,3,} }; cin >> p; cout << p << endl; cout << pp[0] << endl; //Subscript operator overload point p(2, 10); cout << p; cout << p[0] << ',' << p[1] << endl;//It is actually p.operator[](0); p.operator[](1); p[0] = 0; p[1] = 1; cout << p; //Addition + operator overload point p(1, 2), q(5, 6); cout << p << q; cout << p + q; // Internal p.operator+(q); External p.operator+(p, q) return 0; }
11, string type and destructor
class String { char* date;//C-style string int n;//Number of characters public: ~String() {//Destructor if (date) delete[] date; cout << n << "Destructor\n"; } #if 1 String(String& s) {//Default copy constructor hard copy cout << "copy constructor \n"; date = new char[s.n + 1]; n = s.n; for (int i = 0; i < n; i++) date[i] = s[i]; date[n] = '\0'; } #endif String(const char* s=0) {//Constructor cout << "Constructor\n"; if (s == 0) { cout << "s==0\n"; date = 0; n = 0; return; } else { const char* p = s; while (*p != '\0') p++; n = p - s; date = new char[n+1]; for (int i = 0; i < n; i++)//Initialization assignment date[i] = s[i]; date[n] = '\0'; } } char operator[](int i)const {//Used to access if (i < n && i >= 0) return date[i]; else throw"Illegal subscript!\n"; } char& operator[](int i) {//Used to modify if (i < n && i >= 0) return date[i]; else throw"Illegal subscript!\n"; } int size() { return n; }//Returns the number of characters friend ostream& operator<<(ostream& o, String s); }; ostream& operator<<(ostream& o, String s) { for (int i = 0; i < s.size(); i++) { cout << s[i]; } return o; } void f() { String str1, str2("hallo world"); cout << "Before copying\n"; str2[1] = 'E'; cout << "After copying\n"; #if 1 str2[6] = 'W'; cout << str2 << endl;//copy constructor String s3 = str2;//copy constructor s3[0] = 'o'; cout << str2 << endl;//copy constructor cout << s3 << endl;//copy constructor #endif } int main() { f(); }
12, Derivation, inheritance, virtual function
//Inheritance and derivation: a derived class //Inherit from one or more parent class es / base class es, //That is, it inherits the properties and behaviors of the parent class, but it also has its own exclusive properties class Employee { string name; public: virtual void print() {//Virtual is the keyword for virtual functions cout << name << endl; } Employee(string s = "no_Name") { name = s; } string get_name() { return name; } }; //Note that the derived format is followed by: base class class Manager :public Employee{//manager is a derivative of employee //The name of employee is inherited here int level; public: Manager(string n, int l) :Employee(n), level(l) {} void print(); }; //Pay attention to the format of external implementation class objects void Manager::print() { cout << get_name() << '\t' << level << endl; } //You can also derive a class from multiple classes class One { }; class Two { }; //Note the format here. After the inherited class, add: public base class. If you inherit multiple base classes, separate them with class Multiple :public One, public Two { }; int main() { string name; int lev; char sss; Employee* arr[10]; int num = 0; cout << "Please enter a command, m Represents the manager, e Represents an employee\n"; while (cin >> sss) { if (sss == 'm' || sss == 'M') { cout << "Please enter name and level\n"; cin >> name >> lev; Manager* p = new Manager(name, lev); arr[num] = p; num++; } else if (sss == 'e' || sss == 'E') { cout << "Please enter your name\n"; cin >> name; Employee* p = new Employee(name); arr[num] = p; num++; } else break; cout << "Please enter a command\n"; } for (int i = 0; i < num; i++) { arr[i]->print(); } return 0; }
13, Inline function
//Inline function keyword: inline // For functions that do not contain loops, you can use inline functions, // At compile time, the compiler directly replaces with code without creating function expansion, which can reduce the call overhead inline double distance(double a, double b) { return sqrt(a * a + b * b); } int main() { cout<<distance(1, 2); //Actually cout < < sqrt (a * a + b * b); return 0; }
summary
C transition C + + seems simple, but in fact, we should be familiar with the transformation from process-oriented to object-oriented programming. A learning note of this composition should have many deficiencies and imperfections, and study hard.