C++ Object-Oriented Programming (Learning Notes)

C++ Object-Oriented Programming Learning Notes

1. Reference

  • 1. A reference does not define a new variable, but gives an alias to an existing variable. The compiler does not open up memory space for the reference variable. It shares a memory space with the referenced variable.

Examples are as follows:

#include<iostream>
using namespace std;
int main(){
	int x = 5;
	int &y = x;
	y = 20;
	cout<<"x = "<<x<<endl;
	cout<<"y = "<<y<<endl;
	int &z = y;
	z = 30;
	cout<<"x = "<<x<<endl;
	cout<<"y = "<<y<<endl;
	cout<<"z = "<<z<<endl;
}

In the above code, x is referenced by Y and z, so change any value of x,y,z
Then the three values x, y, z will be changed (equivalent to three titles for a person, who will respond to you regardless of which one is called)

  • 2. The nature of the citation
    1. References must be initialized when defined
    2. A variable can have multiple references
    3. Once a reference refers to a variable, it cannot refer to another variable
    4. References can only refer to variables, not constants and expressions

2. Pointer

1. Function of the pointer: Indirect access to memory through the pointer

  • Memory numbers are recorded from 0, usually in hexadecimal digits
  • Addresses can be saved using pointer variables

2. Definition and use of pointers

Examples are as follows:

#include<iostream>
using namespace std;
int main() {
	//Define Pointer
	int a = 10;
	//Syntax for pointer definition: data type * pointer variable name;
	int* p;
	//Let the pointer record the address of the variable a
	p = &a;//Prefix a with an address symbol

	cout << "a The address is: " << &a << endl;
	cout << "Pointer p For: " << p << endl;

	//Use Pointer
	//Memory between pointers can be found by dereferencing 
	//That is, before pointer p, add a * to indicate that the dereference finds the data in memory that the pointer points to

	*p = 1000;
	cout << "a = " << a << endl;
	cout << "*p = " << *p << endl;

	system("pause");
	return 0;
}


This is the result of running the code

3. Memory space occupied by pointers

Examples are as follows:

#include<iostream>
using namespace std;
int main() {
	//Memory space occupied by pointers	
	int a = 10;
	int* p = &a;

	//32-bit operating systems account for 4 bytes, 64 for 8 (any data type)
	cout << "sizeof(int *) = " << sizeof(p) << endl;
	cout << "sizeof(float *) = " << sizeof(float *) << endl;
	cout << "sizeof(double *) = " << sizeof(double*) << endl;
	cout << "sizeof(char *) = " << sizeof(char*) << endl;

	system("pause");
	return 0;
}

4. Null and field pointers

Null pointer: pointer variable points to space numbered 0 in memory
Purpose: Initialize pointer variables
Note: The memory of the null pointer is not accessible

An example of a null pointer is as follows:

#include<iostream>
using namespace std;
int main() {
	//Null pointer
	//1. A null pointer is used to initialize pointer variables
	int* p = NULL;

	//2. The null pointer is not accessible
	//Memory numbers between 0 and 255 are occupied by the system and are therefore inaccessible
	*p = 100;//Writing this will make an error
	cout<<*p<<endl;

	system("pause");
	return 0;
}

An example of a field pointer is as follows:
Field pointer: pointer variable points to illegal memory space

#include<iostream>
using namespace std;
int main() {
	//Field Pointer
	//Pointer variable p points to space with address number 0x1100
	int* p = (int *)0x1100;

	//Access Field Pointer Error
	cout<<*p<<endl;

	system("pause");
	return 0;
}

Summary: Neither the null pointer nor the wild pointer is the space we are requesting, so don't visit it.

2. Combination of pointer and array pointer with function

  • Pointer and Array
    Role: Use pointers to access array elements
#include<iostream>
using namespace std;
int main(){
	int arr[] = {1,2,3,4,5,6,7,8,9,10};
	int *p = arr;//A pointer to an array points to the array's first address (the array name and the array's first address) at this time.
	for(int i = 0;i < 10;i++){
		cout<<*p<<endl;
		p++;//P is the pointer to the address*p is the value of the p address
	}
	
	return 0;
}
  • Pointers and functions
    Role: Using the pointer as a function parameter, you can modify the value of the argument
#include<iostream>
using namespace std;

void swap01(int a ,int b) {
	int temp = a;
	a = b;
	b = temp;
	cout << "swap01 a = " << a << endl;
	cout << "swap01 b = " << b << endl;
}
void swap02(int *p1, int *p2) {
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
	cout << "swap02 a = " << *p1 << endl;
	cout << "swap02 b = " << *p2 << endl;
}
int main() {
	//1. Value transfer
	int a = 10;
	int b = 20;

	swap01(a, b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	//Address Delivery

	swap02(&a, &b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	system("pause");

	return 0;
}

3.const, static, this keyword

  • 1. The keyword const is used to define a read-only variable. The value of the variable defined by the const is not allowed to be changed, that is, it is not allowed to be reassigned, even if it is assigned the same value. So it defines a read-only variable, which means that it must be given an initial value at the time of definition.

4. Operator overload

c++ predefined operators, can only be used for operations of basic data types: integer real character logical type...
But you can't compute between objects, so you have the concept of operator overload
Forms of operator overload

  • The essence of operator overload is function overload
  • It can be overloaded as either a normal function or a member function
  • Converts an expression containing an operator to a call to an operator function
  • Converts the operand of an operator to a parameter of an operator function
  • When an operator is overloaded multiple times, the type of argument determines which operator function to call.

Forms of operator overload

return type operator operator(parameter list)
{
	......
}
#include<iostream>
using namespace std;
class Complex
{
public:
	double real, imag;
	Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) { }
	Complex operator-(const Complex& c);//Member function
};
Complex operator+(const Complex& a, const Complex& b)//General function
{
	return Complex(a.real + b.real, a.imag + b.imag);//Return a temporary object
}
Complex Complex::operator-(const Complex& c)
{
	return Complex(real - c.real, imag - c.imag);//Return a temporary object
}
//When overloaded as a member function, the number of parameters is one minus the number of operators.
//When overloading a normal function, the number of parameters is the number of operators.

int main()
{
	Complex a(4, 4), b(1, 1), c;
	c = a + b;//Equivalent to c=operator+(a,b);
	cout << c.real << "," << c.imag << endl;
	cout << (a - b).real << "," << (a - b).imag << endl;//a-b is equivalent to a.operator-(b)
	return 0;
}

5. Inheritance

The purpose of inheritance is to achieve code reuse

Concepts of inheritance and derivation

  • Inheritance: When defining a new class B, if it is similar to an existing class A (meaning that B has all the features of A), then A can be used as a base class and B as a derived class (also called a subclass) of the base class.
  • Derived classes are derived by modifying and extending the base class. In derived classes, new member variables and member functions can be expanded
  • Once defined, derived classes can be used independently of the base class.
  • Derived classes have all member functions and member variables of the base class, whether private, protected, public.
  • private members in base classes cannot be accessed in member functions of derived classes

Writing of derived classes

class Derived class name: public Base Class Name
{

};

6. Polymorphism

Virtual Functions and Polymorphisms

virtual function

  • In the definition of a class, a member function preceded by the virtual keyword is a virtual function.
class base()
{
	virtual int get();
};
int base::get();
  • The virtual keyword is only used in function declarations in class definitions, not in body writing.
  • Constructors and static member functions cannot be virtual functions
  • Difference between virtual function and normal function, virtual function can participate in polymorphism, normal function can not
  • A pointer to a derived class can be assigned to a pointer to a base class
  • When a dummy function with the same name in a base class and a derived class is called through a base class pointer:
    (1) If the pointer points to an object of a base class, the virtual function of the base class is called;
    (2) If the pointer points to an object of a derived class, the called is a virtual function of the derived class;
    This mechanism is called polymorphism.

The code is as follows:

#include <iostream> 
using namespace std;

class Shape {
protected:
    int width, height;
public:
    Shape(int a = 0, int b = 0)
    {
        width = a;
        height = b;
    }
    virtual int area()//Without the virtual function modification, polymorphism cannot be represented.
    {
        cout << "Parent class area :" << endl;
        return 0;
    }
};
class Rectangle : public Shape {
public:
    Rectangle(int a = 0, int b = 0) :Shape(a, b) { }
    int area()
    {
        cout << "Rectangle class area :" << endl;
        return (width * height);
    }
};
class Triangle : public Shape {
public:
    Triangle(int a = 0, int b = 0) :Shape(a, b) { }
    int area()
    {
        cout << "Triangle class area :" << endl;
        return (width * height / 2);
    }
};
// Principal Functions of Programs
int main()
{
    Shape* shape;
    Rectangle rec(10, 7);
    Triangle  tri(10, 5);
    // Address of storage rectangle
    shape = &rec;
    // Call area function of rectangle
    shape->area();
    // Store the address of a triangle
    shape = &tri;
    // Call area function of triangle
    shape->area();
    return 0;
}

7. Input, output and templates

8.STL Standard Library

1.string class

  • String class is a template class, use string class to include header file
  • Initialization of string object:
    1.string s1("Hello");
    2.string month = "March";
    3.string s2(8,'x');// 8 x
  • The length of the string object is read by the member function length();
    string s;
    cout<<s.length()<<endl;
  • string supports getline functions
    string s;
    getline(cin,s);
  • 1. Copy with assign member function
    string s1("catpig"),s2;
    s2.assign(s1);// Copy All
    s2.assign(s1,1,3);// Partial copy, starting with a character subscripted to 1 and copying 3 characters
  • 2. Assignment of a single character
    s2[5] = s1[3] = 'a';
  • 3. Access characters in string objects one by one
    string s1("Hello");
    for(int i=0;i<s1.length(),i+++)
    Cout< s1.at(i)< endl;// The member function at does range checking, and the subscript operator [] does not.
  • 4. Connect strings with + operators
    string s1("good"),s2("morning!");
    s1+=s2;
    cout<<s1;
  • 5. Connect strings with member function append
    string s1("good"),s2("morning!");
    s1.append(s2);
    s2.append(s1,3,s1.size()); // From subscript 3 to s1.size(); (number of S1 characters)
  • 6. Compare string sizes with relational operators
    ==,>,>=,<,<=,!=
    Return values are of bool type, true if true, false otherwise.
  • 7. Compare string size with member function compare
    string s1("hello"),s2("hello"),s3("hell");
    int f1 = s1.compare(s2);// Equal to return 0 greater than return 1 less than Return-1
  • 8. Substring member function substr
    s2 = s1.substr(4,5);// Subscript 4 begins, 5 characters
  • 9. swap member function
    s1.swap(s2);// Interchange the values of both
  • 10. Find the character member function find()//rfind() in the string from back to front
    s1.find("a"); // Look for the subscript for the location of'a'after s1 goes there
  • 11. Delete the character member function erase() in string
    s1.erase(5);// Remove subscript 5 and subsequent characters
  • 12. Replace character member function replace() in string
    s1.replace(2,3,'haha'); // Replace the three characters starting with subscript 2 in s1 with "haha"
  • 13. Insert character member function insert() into string
    s1.insert(5,s2);// Insert S2 into position of s1 subscript 5
  • 14. Convert string type to char type s1.c_str()

2. Basic concepts of STL

  • Container: A generic data structure that can accommodate a variety of data types and is a class template
  • Iterator: Can be used to access elements in containers in turn, similar to a pointer
  • Algorithms: Function templates for manipulating elements in containers

Container type
1. Sequential Containers
vector , deque , list
2. Associated Containers
set , multiset , map , multimap
3. Container adapters
stack , queue priority_queue

2.STL Vector Container

Tags: C++

Posted on Sat, 04 Dec 2021 12:45:35 -0500 by Aliz