当前位置:网站首页>Classes and objects (4)
Classes and objects (4)
2022-06-11 21:44:00 【Code loving students】
Catalog
1.2 Use of initialization list
1. Supplement to constructor
1.1 Constructor assignment
stay Classes and objects (2) In, we talked about that when an object is created, the constructor will be called to assign values to member variables , So is this assignment initialization ?
class Date
{
public:
Date(int year=1, int month=1, int day=1)
{
_year = year;
_month = month;
_day = day;
_year=2;
_month=1;
_day=3;
}
private:
int _year;
int _month;
int _day;
};Although after the above constructor call , Object already has an initial value , But you can't call it initialization of class object members , The statement in the constructor body can only call it as an initial value , It can't be called initialization . Because initialization can only be initialized once , The constructor body can be assigned multiple times .
Then we have to think about a problem : What if there are certain members in our member variables that need to be initialized at the time of creation ?
such as int&, Previously, we learned that when using references , We have to initialize it , The constructor here cannot provide , that C++ Just added a new thing to the constructor -- Initialization list .
1.2 Use of initialization list
Start with a colon , Then there is a comma separated list of data members , Each member variable is followed by an initial value or expression in parentheses .
class Date
{
public:
Date(int year, int month, int day)
:_year(year)
,_month(month)
,_day(day)
{}
private:
int _year;
int _month;
int _day;
};
Be careful :
1. Each variable in the initialization list can only be initialized once , Because initialization can only be initiated once

2. If the class contains reference member variables 、const Member variables 、 Custom type members ( This class has no default constructor ), It must be placed in the initialization list for initialization , Because it cannot be initialized in the constructor .
3. After learning the initialization list , When no matter what kind of member variable you encounter , We all suggest to put it in the initialization list for initialization .
4. The initialization order in the initialization list is based on the order in which member functions are declared
class A
{
public:
A(int a)
:_a1(a)
,_a2(_a1)
{}
void Print() {
cout<<_a1<<" "<<_a2<<endl;
}
private:
int _a2;
int _a1;
}
int main() {
A aa(1);
aa.Print();
}The current code will output 1 And random values , This is because _a2 and _a1 The statement is _a2 First , Therefore, in the initialization list, first carry out the following statement , Then execute the above statement .
1.3 explicit keyword
explicit The moral is to show the meaning of , So what's its function ?
class Date
{
public:
Date(int year)
:_year(year)
{}
private:
int _year;
int _month:
int _day;
};
void TestDate()
{
Date d1(2018);
d1 = 2019;
}When the constructor is a single argument , Let's assign a value to the object. Will this cause a problem ?

We found that there would be no problem here , Because there are implicit transformations in the compiler , Will use 2019 This value is used to create an unnamed object , Use this object to create a for d1 assignment .
But let's look at this code , If you don't know the implicit conversion , Is it difficult to understand whether what is written here is correct , So we used explicit Keyword to decorate the constructor , Make this poorly readable code disappear .
2. static
2.1 Concept
Declare as static A class member of a class is called a static member of a class , use static Modified member variables , Call it static member variable ,
By static Decorated member function , Called static member function , Static member variables must be initialized outside the class .
2.2 features
1. Static members are shared by all class objects , It doesn't belong to a specific instance
2. Static member variables must be defined outside the class , Do not add... When defining static keyword
3. Class static members are available class names :: Static members or objects . Static members to access

4. Static member functions do not belong to any object , No hidden this The pointer , Cannot access any non static members
5. Static members are like ordinary members of a class , Also have public、protected、private3 Access levels , You can also have a return value
3. Friends
3.1 The concept of friends
1. Friends are divided into friend functions and friend classes
2. Friends provide a way to break through encapsulation , But increased coupling , So try to avoid using
3.2 Friend function
If we want to achieve <<、>> An object , Then we have to overload these two operators
But we can't overload these two operands in a class , because cout and cin And hidden in member functions this The pointer competes for the position of the first parameter , Then we can only define it outside the class . But how do we access private member variables in a class ?
At this time, our friends play a corresponding role :

We define functions outside the class , Use... In classes friend Keyword to declare that this function is mine “ friend ”, But remember that this friend is one-way .
Be careful :
1. Friend functions can access all member variables in the class , But it is not a member function .
2. Friend function cannot be used const To modify
3. Friend functions can be declared anywhere in the class definition , No access restrictions
4. A function can be a friend function of multiple classes
3.3 Friend class
If I want to access member variables of another class in one class , But I have no authority , So what should I do ?
This is when we think of friends , We can define access classes in classes , Make it my “ friend ”, So I can access its member variables .
When added friend Statement of , We can use Time Private member variables in the class .
3.4 Friend characteristics
1. Friendship is one-way , Not exchangeable .
2. Friendship cannot be transmitted If B yes A Friends ,C yes B Friends , Can't explain C when A Friends .
边栏推荐
- Binary search - Learning
- Leetcode-98- validate binary search tree
- RPA+低代码助推品牌电商启新创变、重启增长
- Relatively perfect singleton mode
- LeetCode-322-零钱兑换
- 8、 BOM - chapter after class exercises and answers
- 实验10 Bezier曲线生成-实验提高-交互式生成B样条曲线
- C语言实现八种排序(2)
- Master of a famous school has been working hard for 5 years. AI has no paper. How can the tutor free range?
- 快速排序的三种方法
猜你喜欢

EndnoteX9簡介及基本教程使用說明

类和对象(1)

C语言实现八种排序 - 归并排序

The upcoming launch of the industry's first retail digital innovation white paper unlocks the secret of full link digital success

Apache local multi port configuration
![[Part 13] source code analysis and application details of completabilefuture class [key]](/img/cf/87c60a1d46835f3f0dae9f44970de4.jpg)
[Part 13] source code analysis and application details of completabilefuture class [key]

LaTex实战笔记 3-宏包与控制命令

LeetCode-98-验证二叉搜索树

行而不辍,未来可期|云扩科技入选上海市专精特新企业

华为设备配置H-VPN
随机推荐
Expérience 10 génération de courbes bezier - amélioration expérimentale - génération de courbes B - spline par point de contrôle
LeetCode-43-字符串相乘
Top - k问题
CANN编码的一些报错汇编
[Part 15] use and basic principle of forkjoinpool [key]
Endnotex9 introduction and basic tutorial instructions
动态内存管理(1)
Why is rpa+ low code a powerful tool to accelerate the digital transformation of finance?
RPA super automation | nongnongji and cloud expansion accelerate financial intelligent operation
Chain storage structure of linear table
如何查看win系统的安装日期
Binary search - Learning
67. 二进制求和
JVM|前言介绍
bzoj3188 Upit
判断大小端存储两种办法
Sword finger offer 29 Print matrix clockwise
Apache local multi port configuration
作为一名 ABAP 资深顾问,下一步可以选择哪一门 SAP 技术作为主攻方向?
LeetCode-98-验证二叉搜索树