current position:Home>C++ 5 | composition and inheritance

C++ 5 | composition and inheritance

2022-06-24 09:22:436 seven

5、 ... and 、 Combination and inheritance

1、 Review criteria io flow

stay C In language , The keyboard input print information is as follows

#include <stdio.h>

int main()
{
    
    printf("input:");fflush(stdout);
    
    char buf[100];
    fgets(buf);
    
    printf("%s\n",buf);
}

Running results

@ubuntu:/mnt/hgfs/ub2$ gcc cin_cout1.c
cin_cout1.c: In function ‘main’:
cin_cout1.c:8:5: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
     gets(buf);
     ^~~~
     fgets
/tmp/ccOXH43A.o: In function `main': cin_cout1.c:(.text+0x44): warning: the `gets' function is dangerous and should not be used.
@ubuntu:/mnt/hgfs/ub2$ ./a.out
input:dskfjsdoj
dskfjsdoj
@ubuntu:/mnt/hgfs/ub2$ 

example 22、 stay C++ in ,io Stream representation

#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{
 //   printf("input:");fflush(stdout);
    cout<<"input:";
    char buf[100];
//    gets(buf);
    cin>>buf;
//    printf("%s\n",buf);
    cout<<buf<<endl;
}

Running results

@ubuntu:/mnt/hgfs/ub2$ g++ cin_cout2.cpp 
@ubuntu:/mnt/hgfs/ub2$ ./a.out
input:soadjaofaoh
soadjaofaoh
@ubuntu:/mnt/hgfs/ub2$ 

Of course , In addition, you can print numbers directly , And its corresponding hexadecimal number

#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{
 //   printf("input:");fflush(stdout);
    cout<<"input:";
    char buf[100];
//    gets(buf);
    cin>>buf;
//    printf("%s\n",buf);
    cout<<buf<<endl;

    cout<<10<<endl;
    cout<<hex<<10<<endl;
}

Running results

@ubuntu:/mnt/hgfs/ub2$ g++ cin_cout3.cpp 
@ubuntu:/mnt/hgfs/ub2$ ./a.out
input:dsofhsighshgo
dsofhsighshgo
10
a
@ubuntu:/mnt/hgfs/ub2$ 

2、 Combine

If you need to do an application of student management system now , Then I remembered that I had done a class with tail addition function before , There is a chance to use , therefore , The combination comes in handy .

for instance , The tail append function array class we did before is called ARR, Now I want to use it in the current student management system class stuma in , The implementation is as follows

example 23、 Combine

arr.cpp

#include "arr.h"
#include <stdio.h>

//ARR Class ,addtail and show
void ARR::addtail(int data)
{
	this->data[tail++] = data;
}

void ARR::show(void)
{
	int i = 0;
	for(;i<tail; i++)
		printf("%d, ", data[i]);
	printf("\n");
}

arr.h

#ifndef _ARR_
#define _ARR_

class ARR{
public:
	ARR():tail(0){
	}

	void addtail(int data);
	void show(void);
private:
	int data[100];
	int tail;
};


#endif

main.cpp

#include "arr.h"

class Stuma{
public:
	Stuma(){

	}
	~Stuma() { }
	
	void savescore(int score)
	{
		scorearr.addtail(score);
	}

	void showscore(void)
	{
		scorearr.show();
	}

private:
	ARR scorearr;

};

int main()
{
	Stuma mmm;

	mmm.savescore(23);
	mmm.savescore(44);
	mmm.savescore(55);
	mmm.savescore(23);

	mmm.showscore();
}

Running results

@ubuntu:/mnt/hgfs/ub2/ARR1$ g++ *.cpp
@ubuntu:/mnt/hgfs/ub2/ARR1$ ./a.out
23, 44, 55, 23, 
@ubuntu:/mnt/hgfs/ub2/ARR1$ 

In case of addtail() Originally belongs to ARR Class , Let it be combined with other functions ( This example does not combine other function implementations ) Encapsulate again , Get belong to stuma Class savescore(), Empathy ,ARR Class show() After re encapsulation, we get stuma Class showscore(). The schematic diagram is as follows

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-u7dzRkSj-1655908744452)(D:\Typora_pic\1655434361516.png)]

The beauty of combination is to make the function of others for your own use , Many times we are exposed to this situation : Developing things requires A、B、C、D And so on , Then you have something on hand A、B、C、D Resources of function implementation leaders ( Open source online 、 Provided by the company, etc ), So you can use the combination to integrate the functions of these big guys for your own use . otherwise , You have to do it yourself ABCD The function of , This not only takes time and energy , And there are likely to be all kinds of bug, Quality is not guaranteed .( After all, the big guy's code is the essence that has been honed )

3、 Inherit

example 24、 Inherit (1)

First , Simple printing x To screen

#include <iostream>

using namespace std;

class A{
public:
	A(){ }
	~A(){ }
	void showx()
	{
		cout<<"xxxxxxxxxxxxxxx"<<endl;
	}
};


int main()
{
	A a;
	a.showx();
}

Execution results

@ubuntu:/mnt/hgfs/ub2$ g++ base1_1.cpp 
@ubuntu:/mnt/hgfs/ub2$ ./a.out
xxxxxxxxxxxxxxx
@ubuntu:/mnt/hgfs/ub2$ 

Now I want to print y instead of x, namely a.showy(), Obviously not , So it is necessary to show Function upgrade .

There are two situations :

  1. Can get the source code

This is a simple case , Directly in the corresponding class (class A) Add corresponding functions in

void showy()
	{
		cout<<"yyyyyyyyyyyyyyy"<<endl;
	}
  1. Can't get the source code

But many times you can't get other people's source code , And want to use other people's similar functions , So you need to inherit ( The derived ).

The expression is as follows

class AX:public A{
    
};

AX yes A The derived class , Although you can't get other people's classes A, But it can be applied to classes A Derive your own class AX, Then class AX It inherits the class A The function of . Next, you just need to do the class AX Carry out your own programming operations and add the required functions , You can not only implement your own functions, but also have inherited classes A The function of .

The case is as follows

#include <iostream>

using namespace std;

class A{
public:
	A(){ }
	~A(){ }
	void showx()
	{
		cout<<"xxxxxxxxxxxxxxx"<<endl;
	}
};

class AX:public A{
public:
	void showy()
	{
		cout<<"yyyyyyyyyyyyyyy"<<endl;
	}
};

int main()
{
	AX b;
	b.showx();
	b.showy();
}

Execution results

@ubuntu:/mnt/hgfs/ub2$ g++ base1_2.cpp 
@ubuntu:/mnt/hgfs/ub2$ ./a.out
xxxxxxxxxxxxxxx
yyyyyyyyyyyyyyy
@ubuntu:/mnt/hgfs/ub2$ 

You can find , class AX Not only have their own print y function , And it inherits the class A Printing of x function ( It can also be said to be a class A Derived Print x The function of gives AX).

The distinction between composition and inheritance :

Composition is the integration of excellent function realization as its own function ; And inheritance ( The derived ) It is to add your own functions on the basis of excellent function realization , The efficiency of standing on the shoulders of giants .

for instance : If my need is a black line , Then the combination is to closely line up the black spots to form a black line ; If I need a red line , So inheritance is based on other people's lines , Then dye it red .

example 25、 Inherit (2)

Now let's take a more complicated example :

Looking back 23, as follows

arr.cpp

#include "arr.h"
#include <stdio.h>

//ARR Class ,addtail and show
void ARR::addtail(int data)
{
	this->data[tail++] = data;
}

void ARR::show(void)
{
	int i = 0;
	for(;i<tail; i++)
		printf("%d, ", data[i]);
	printf("\n");
}

arr.h

#ifndef _ARR_
#define _ARR_

class ARR{
public:
	ARR():tail(0){
	}

	void addtail(int data);
	void show(void);
private:
	int data[100];
	int tail;
};


#endif

main.cpp

#include "arr.h"

class Stuma{
public:
	Stuma(){

	}
	~Stuma() { }
	
	void savescore(int score)
	{
		scorearr.addtail(score);
	}

	void showscore(void)
	{
		scorearr.show();
	}

private:
	ARR scorearr;

};

int main()
{
	Stuma mmm;

	mmm.savescore(23);
	mmm.savescore(44);
	mmm.savescore(55);
	mmm.savescore(23);

	mmm.showscore();
}

This is to simulate the function of the student management system . Now we say that we should add the function of seeking average on the original basis , If it is a general case , Just go to arr.cpp and arr.h Add functionality , similar addtail() and show() like that . as follows

arr.cpp

#include "arr.h"
#include <stdio.h>


void ARR::addtail(int data)
{
	this->data[tail++] = data;
}

void ARR::show(void)
{
	int i = 0;
	for(;i<tail; i++)
		printf("%d, ", data[i]);
	printf("\n");
}

int ARR::ever(void)
{
	int i = 0;
	int sum = 0;
	for(;i<tail; i++)
		sum += data[i]; 
	return sum/tail;
}

arr.h

#ifndef _ARR_
#define _ARR_

class ARR{
public:
	ARR():tail(0){
	}

	void addtail(int data);
	void show(void);
	int ever(void);
private:
	int data[100];
	int tail;
};


#endif

main.cpp

#include "arr.h"
#include <iostream>

using namespace std;
class Stuma{
public:
	Stuma(){

	}
	~Stuma() { }
	
	void savescore(int score)
	{
		scorearr.addtail(score);
	}
	
	int everscore(void)
	{
		return scorearr.ever();
	}

	void showscore(void)
	{
		scorearr.show();
	}

private:
	ARR scorearr;
};

int main()
{
	Stuma mmm;

	mmm.savescore(23);
	mmm.savescore(44);
	mmm.savescore(55);
	mmm.savescore(23);

	mmm.showscore();
	cout<<mmm.everscore()<<endl;
}

Execution results :

@ubuntu:/mnt/hgfs/ub2/ARR2_1$ g++ *.cpp 
@ubuntu:/mnt/hgfs/ub2/ARR2_1$ ./a.out
23, 44, 55, 23, 
36
@ubuntu:/mnt/hgfs/ub2/ARR2_1$ 

However , Most of the time you can't get other people's arr file , In this case, you need to use inheritance to implement . Start with ARR To derive its own class from ARRX, And then in ARRX Add function in , And then put ARRX Combine to class stuma. as follows

arr.cpp

#include "arr.h"
#include <stdio.h>

void ARR::addtail(int data)
{
	this->data[tail++] = data;
}

void ARR::show(void)
{
	int i = 0;
	for(;i<tail; i++)
		printf("%d, ", data[i]);
	printf("\n");
}

arr.h

#ifndef _ARR_
#define _ARR_

class ARR{
public:
	ARR():tail(0){
	}

	void addtail(int data);
	void show(void);
private:
	int data[100];
	int tail;
};

#endif

main.cpp

#include "arr.h"
#include <iostream>

using namespace std;

class ARRX:public ARR{
public:
	int ever(void)
	{
		int i = 0;
		int sum = 0;
		for(;i<tail; i++)
			sum += data[i]; 
		return sum/tail;
	}
};

class Stuma{
public:
	Stuma(){

	}
	~Stuma() { }
	
	void savescore(int score)
	{
		scorearr.addtail(score);
	}
	
	int everscore(void)
	{
		return scorearr.ever();
	}

	void showscore(void)
	{
		scorearr.show();
	}

private:
	ARR scorearr;
};

int main()
{
	Stuma mmm;

	mmm.savescore(23);
	mmm.savescore(44);
	mmm.savescore(55);
	mmm.savescore(23);

	mmm.showscore();
	cout << mmm.everscore() <<endl;
}

Error in execution result

[email protected]:/mnt/hgfs/ub2/level14/2day/ARR2_2$ g++ *.cpp 
main.cpp: In member function ‘int ARRX::ever()’:
main.cpp:12:10: error: ‘int ARR::tail’ is private within this context
   for(;i<tail; i++)
          ^~~~
In file included from main.cpp:1:0:
arr.h:13:6: note: declared private here
  int tail;
      ^~~~
main.cpp:13:11: error: ‘int ARR::data [100]’ is private within this context
    sum += data[i];
           ^~~~
In file included from main.cpp:1:0:
arr.h:12:14: note: declared private here
  int data[100];
              ^
main.cpp:14:14: error: ‘int ARR::tail’ is private within this context
   return sum/tail;
              ^~~~
In file included from main.cpp:1:0:
arr.h:13:6: note: declared private here
  int tail;
      ^~~~
main.cpp: In member function ‘int Stuma::everscore()’:
main.cpp:32:19: error: ‘class ARR’ has no member named ‘ever’
   return scorearr.ever();
                   ^~~~
[email protected]:/mnt/hgfs/ub2/level14/2day/ARR2_2$ 

This is because public In inheritance mode , All of the base class private Members are not accessible in derived classes

class ARRX:public ARR//ARRX Is a derived class ,ARR Is the base class ,public Indicates the mode of inheritance 

About the way of inheritance , Shown below

 Insert picture description here

So the reason for the error is that the private member (private) Be restricted , There is also a mistake : class ARR Dispatch generation ARRX after , The combination should be ARRX instead of ARR, See the error prompt

main.cpp: In member function ‘int Stuma::everscore()’:
main.cpp:32:19: error: ‘class ARR’ has no member named ‘ever’
   return scorearr.ever();

So the arr.h The private members of , then main.cpp Class stuma The private member is changed to ARRX Of , as follows

arr.cpp

#include "arr.h"
#include <stdio.h>

void ARR::addtail(int data)
{
	this->data[tail++] = data;
}

void ARR::show(void)
{
	int i = 0;
	for(;i<tail; i++)
		printf("%d, ", data[i]);
	printf("\n");
}

arr.h

#ifndef _ARR_
#define _ARR_

class ARR{
public:
	ARR():tail(0){
	}

	void addtail(int data);
	void show(void);
//private:
	int data[100];
	int tail;
};

#endif

main.cpp

#include "arr.h"
#include <iostream>

using namespace std;

class ARRX:public ARR{
public:
	int ever(void)
	{
		int i = 0;
		int sum = 0;
		for(;i<tail; i++)
			sum += data[i]; 
		return sum/tail;
	}
};

class Stuma{
public:
	Stuma(){

	}
	~Stuma() { }
	
	void savescore(int score)
	{
		scorearr.addtail(score);
	}
	
	int everscore(void)
	{
		return scorearr.ever();
	}

	void showscore(void)
	{
		scorearr.show();
	}

private:
	ARRX scorearr;
};

int main()
{
	Stuma mmm;

	mmm.savescore(23);
	mmm.savescore(44);
	mmm.savescore(55);
	mmm.savescore(23);

	mmm.showscore();
	cout << mmm.everscore() <<endl;
}

Execution results :

@ubuntu:/mnt/hgfs/ub2/ARR2_2$ g++ *.cpp 
@ubuntu:/mnt/hgfs/ub2/ARR2_2$ ./a.out
23, 44, 55, 23, 
36
@ubuntu:/mnt/hgfs/ub2/ARR2_2$ 

copyright notice
author[6 seven],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240749293933.html

Random recommended