Learning C + + (III. encapsulation and overloading)

Posted by EnDee321 on Wed, 09 Mar 2022 09:36:23 +0100

1, Encapsulation

Encapsulation: it is the hiding and modularization of information. It is a method to separate the interface from the implementation. In the study of computer language, we have encapsulated data and function. Object encapsulation encapsulates the data and its operations into a whole object, so that the program can access or modify the data only through the interface provided by the object.
For example, the following program encapsulates a program into three files through modular programming: person h,Person.cpp,main.cpp
Including: person H declaration class; Person. Implementation of CPP class method; main. The main functions of CPP program are realized. The specific program code is as follows:

/*******************Person.h***********************/
#ifndef PERSON_H
#define PERSON_H

#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
    string name = "lili";
public:
    Person();
    void showName();
    void setName(string str);

};
#endif // PERSON_H
/**************Person.cpp**********************/
#include "person.h"
Person::Person()
{
	cout<<"Calling the constructor"<<endl;
}
void Person::showName(){
    cout<<"my name is "<<name<<endl;
}
void Person::setName(string str){
    name = str;
}
/****************main.cpp*********************/
#include "person.h"
int main()
{
    cout<<"kakaka"<<endl;
    Person *p1 = new Person();
    p1->showName();
    p1->setName("ivan");
    p1->showName();
    return 0;
}

2, Heavy load

The key and difficult points in c + + language are overloading, polymorphism and template. Here we first introduce overloading.
Overload (static binding: binding at compile time): different parameters with the same name (same function name, different parameter type, number and order), intelligent matching (at call time).
Principle: the compiler determines the most suitable definition by comparing the parameter type you use with the parameter type you define.

1. Function overload:
Functions with similar functions, but with different details, can take the same name and adapt automatically to avoid trouble. (Note: it cannot be distinguished by return value type)

#if 1
/**************Constructor overload****************/
#include <iostream>
#include<string>
using namespace std;
class Person
{
private:
    string name = "lili";
public:
    //Constructor (multiple -- > overloads with the same name)
    Person();
    Person(string str);
    void showName();
};
Person::Person(){
    cout<<name+"create object 1"<<endl;
}
Person::Person(string str)
{
    name = str;
    cout<<name+"create object 2"<<endl;
}
void Person::showName(){
    cout<<"my name is "<<name<<endl;
}

int main()
{
    Person *p1 = new Person();
    p1->showName();

    Person *p2 = new Person("dahua");
    p2->showName();
    return 0;
}
#endif

2. Method overload with the same name

//Example: method overloading with the same name (Note: it cannot be overloaded by return type) 
{//person.h
#ifndef PERSON_H
#define PERSON_H
#include <iostream>

using namespace std;

class Person
{
private:
    string name="baby";
    int age=20;
public:
    Person();
    void show();
    void show(int i);
    void show(string str);
};

#endif // PERSON_H	
}	
{//person.cpp
#include "person.h"

Person::Person(){
}

void Person::show(){
  cout<<"name:"+ name + "  age:"<<age<<endl;
}

void Person::show(int i){
  cout<<"age:"<<age<<endl;
}

void Person::show(string str){
  cout<<"name:"+ name<<endl;
}
	
}		
{//main.cpp
#include "person.h"

int main(int argc, char *argv[])
{
    Person *p1 = new Person();
    //Overloaded methods cannot be used to return the same name (Note: overloaded methods cannot be used to return different types)
    p1->show();
    p1->show(1);  
    p1->show("str");
    return 0;
}	
}

3. The overloaded operator is the meaning given to the existing operator in the class.
Why operator overloading is required: because operator operations are limited to basic data types, sometimes we need to operate on user-defined data types. At this time, operator overloading is required to use operators.
Operator overloaded functions exist in two ways relative to classes: (1) overloaded functions are member functions of classes; (2) Overloaded as a friend function of a class. The following are the contents of overloading as member functions:

Basic format:

type specifier  operator Operator (parameter list)
{
	Function body; //Code for implementing operator function
}
//example:
bool operator >= (const Student & stu) const
{
}
Basic rules of operator overloading
1. Only existing operators can be overloaded, and the following five operators cannot be overloaded: member access operator ', Member pointer operator '*', field operation '::', conditional operator '?:', sizeof operator;
2. Operator overloading does not change the priority, associativity and number of operands;
3. The original semantics will not be changed after operator overloading;
4. The overloaded operation object has at least one user-defined class object (or class object reference), that is, the operator cannot be overloaded for the basic data type;
/********************mhead.h*************************/
#ifndef MHEAD_H
#define MHEAD_H

//Operator overloading 
//Binocular operator overload: overload the addition operator to find the volume
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
    Student(const string& ="",double=0);
    bool operator >= (const Student&) const;
    string GetName()const;
    double GetScore()const;
private:
    string strName;
    double dScore;
};
#endif // MHEAD_H
/***********************main.cpp***************************/
#include <QCoreApplication>
#include "mhead.h"
Student::Student(const string& name,double score)
{
  strName = name;
  dScore = score;
}
//Constant member function: used to compare the size of the data member dScore of two objects
bool Student:: operator >=(const Student& stu) const
{
    return this->dScore >= stu.dScore;
}
string Student::GetName() const
{
    return strName;
}
double Student::GetScore() const
{
    return dScore;
}
int main(int argc, char *argv[])
{
    Student s1("jan",89),s2("ken",98);
    cout<<"Names and grades of students with good grades:";
    if(s1>=s2)
    {
        cout << s1.GetName()<<" "<<s1.GetScore()<<endl;
    }else{
        cout << s2.GetName()<<" "<<s2.GetScore()<<endl;
    }
    return 0;
}

Topics: C++ encapsulation