当前位置:网站首页>(p19-p20) delegate constructor (proxy constructor) and inheritance constructor (using)
(p19-p20) delegate constructor (proxy constructor) and inheritance constructor (using)
2022-06-12 08:26:00 【Ordinary people who like playing basketball】
1. Delegate constructor ( Proxy constructors )
Delegate constructors allow one constructor in the same class to call other constructors , This simplifies the initialization of related variables .- - Here's an example :
#include <iostream>
using namespace std;
class Test
{
public:
Test() {
};
Test(int max)
{
this->m_max = max > 0 ? max : 100;
}
Test(int max, int min)
{
this->m_max = max > 0 ? max : 100; // Redundant code
this->m_min = min > 0 && min < max ? min : 1;
}
Test(int max, int min, int mid)
{
this->m_max = max > 0 ? max : 100; // Redundant code
this->m_min = min > 0 && min < max ? min : 1; // Redundant code
this->m_middle = mid < max&& mid > min ? mid : 50;
}
int m_min;
int m_max;
int m_middle;
};
int main()
{
Test t(90, 30, 60);
cout << "min: " << t.m_min << ", middle: "
<< t.m_middle << ", max: " << t.m_max << endl;
return 0;
}
- test :

There are three constructors in the above program , But in all three functions Duplicate code , stay C++11 Constructors cannot be called before , After adding the delegate structure , We can easily optimize the code :
- eg:
#include <iostream>
using namespace std;
class Test
{
public:
Test() {
};
Test(int max)
{
this->m_max = max > 0 ? max : 100;
}
Test(int max, int min) :Test(max)
{
this->m_min = min > 0 && min < max ? min : 1;
}
Test(int max, int min, int mid) :Test(max, min)
{
this->m_middle = mid < max&& mid > min ? mid : 50;
}
int m_min;
int m_max;
int m_middle;
};
int main()
{
Test t(90, 30, 60);
cout << "min: " << t.m_min << ", middle: "
<< t.m_middle << ", max: " << t.m_max << endl;
return 0;
}
- test :

You can see in the modified code , There is no duplicate code , And in a constructor, we call other constructors for initialization of relevant data. , It's like a call chaining .
- When using delegate constructors, you need to pay attention to several issues :
This chained constructor call cannot form a closed loop ( Dead cycle ), Otherwise, exceptions will be thrown during operation .
If you want to make chained calls to multi-level constructors , It is recommended to write the of the constructor call in the initial list instead of inside the function body , Otherwise, the compiler will prompt for duplicate definitions of formal parameters .
Test(int max)
{
this->m_max = max > 0 ? max : 100;
}
Test(int max, int min)
{
Test(max); // error, The compiler will report an error here , Prompt parameter max Defined repeatedly
this->m_min = min > 0 && min < max ? min : 1;
}
- After initializing a list, we call the proxy constructor to initialize a class member variable. , This variable cannot be initialized again in the initialization list .
// error , The delegate constructor cannot be used again m_max Initialize the
Test(int max, int min) : Test(max), m_max(max)
{
this->m_min = min > 0 && min < max ? min : 1;
}
2. Inheritance constructor
C++11 The inheritance constructor provided in can Let derived classes directly use the constructor of the base class , Without having to write your own constructor , Especially when the base class has many constructors , It can greatly simplify the writing of derived class constructors .
- Let's first look at the processing before there is no inherited constructor :
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base(int i) :m_i(i) {
}
Base(int i, double j) :m_i(i), m_j(j) {
}
Base(int i, double j, string k) :m_i(i), m_j(j), m_k(k) {
}
int m_i;
double m_j;
string m_k;
};
class Child : public Base
{
public:
Child(int i) :Base(i) {
}
Child(int i, double j) :Base(i, j) {
}
Child(int i, double j, string k) :Base(i, j, k) {
}
};
int main()
{
Child c(520, 13.14, "i love you");
cout << "int: " << c.m_i << ", double: "
<< c.m_j << ", string: " << c.m_k << endl;
return 0;
}
- test :

Through the test code, we can see , Initializes class members inherited from the base class in subclasses , You need to redefine the constructor consistent with the base class in the subclass , It's very complicated ,C++11 This problem is perfectly solved by adding the new feature of inheritance constructor in , Make the code simpler .
- The use of inheritance constructors is like this :
By using using Class name :: Constructor name ( In fact, the class name and constructor name are the same ) To declare the constructor using the base class , In this way, the subclass can not define the same constructor , Directly use the constructor of the base class to construct the derived class object .
- eg:
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base(int i) :m_i(i) {
}
Base(int i, double j) :m_i(i), m_j(j) {
}
Base(int i, double j, string k) :m_i(i), m_j(j), m_k(k) {
}
int m_i;
double m_j;
string m_k;
};
class Child : public Base
{
public:
// In the modified subclass , No constructor was added , Instead, it adds using Base::Base;
// In this way, you can directly inherit all constructors of the parent class in the subclass , Through them to construct subclass objects .
using Base::Base;
};
int main()
{
Child c1(520, 13.14);
cout << "int: " << c1.m_i << ", double: " << c1.m_j << endl;
Child c2(520, 13.14, "i love you");
cout << "int: " << c2.m_i << ", double: "
<< c2.m_j << ", string: " << c2.m_k << endl;
return 0;
}
- test :

In addition, if the function with the same name in the parent class is hidden in the subclass , It can also be done through using Use these parent functions in the base class in subclasses
- eg:
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base(int i) :m_i(i) {
}
Base(int i, double j) :m_i(i), m_j(j) {
}
Base(int i, double j, string k) :m_i(i), m_j(j), m_k(k) {
}
void func(int i)
{
cout << "base class: i = " << i << endl;
}
void func(int i, string str)
{
cout << "base class: i = " << i << ", str = " << str << endl;
}
int m_i;
double m_j;
string m_k;
};
class Child : public Base
{
public:
using Base::Base;
using Base::func;
void func()
{
cout << "child class: i'am luffy!!!" << endl;
}
};
int main()
{
Child c(250);
c.func();
c.func(19);
c.func(19, "luffy");
return 0;
}
- test :

summary :
The subclass inherits the constructor of the parent class , Subclasses use methods of hidden parent classes , Use using
Reference resources : Delegate construction and inheritance constructors
边栏推荐
- Group planning chapter I
- 后MES系统的时代,已逐渐到来
- Hands on learning and deep learning -- a brief introduction to softmax regression
- Project sorting of niuke.com
- TMUX common commands
- 只把MES当做工具?看来你错过了最重要的东西
- ctfshow web4
- Website colab and kaggle
- JVM learning notes: three local method interfaces and execution engines
- Record the treading pit of grain Mall (I)
猜你喜欢

Configuration and principle of MSTP

Py & go programming skills: logic control to avoid if else

Vision Transformer | Arxiv 2205 - TRT-ViT 面向 TensorRT 的 Vision Transformer

Ankerui motor protector has the functions of overload inverse time limit, overload definite time limit, grounding, starting timeout, leakage, underload, phase failure, locked rotor, etc

js中的正则表达式

Error: what if the folder cannot be deleted when it is opened in another program

ctfshow web3

Group planning chapter I

Installation series of ROS system (II): ROS rosdep init/update error reporting solution

报错:文件夹在另一个程序中打开无法删除怎么办
随机推荐
MATLAB image processing - cosine noise removal in image (with code)
A brief summary of C language printf output integer formatter
超全MES系统知识普及,必读此文
JVM learning notes: garbage collection mechanism
2.2 linked list - Design linked list (leetcode 707)
MES系统质量追溯功能,到底在追什么?
Vision transformer | arXiv 2205 - TRT vit vision transformer for tensorrt
ctfshow web4
The era of post MES system has come gradually
Prediction of COVID-19 by RNN network
Record the first step pit of date type
Principle and configuration of MPLS
Hands on learning and deep learning -- Realization of linear regression from scratch
What kind of sparks will be generated when the remote sensing satellite meets the Beidou navigation satellite?
GTEST/GMOCK介绍与实战
Hands on deep learning -- weight decay and code implementation
Model compression | tip 2022 - Distillation position adaptation: spot adaptive knowledge distillation
Never use MES as a tool, or you will miss the most important thing
如何理解APS系统的生产排程?
JVM学习笔记:三 本地方法接口、执行引擎