[英]Passing 'this' within braces to an object of a class in C++
class District
:public State<District>
{
public:
typedef Citizen Man;
using State<District>::State;
void CheckTransition( Man& Man );
private:
int counter = 0;
};
class Citizen
:public TopState<Citizen>
{
public:
Citizen();
District object{this};
};
I am unable to understand the usage of the last line in this piece. 我无法理解本文最后一行的用法。 Can some one please explain what is happening here?
有人可以解释一下这里发生了什么吗?
Line: District object{this};
行:
District object{this};
I would like to understand the usage of this
in this context within the braces to an object of a class. 我想了解的使用
this
在括号内这方面的类的对象。
Line: District object{this};
行:地区对象{this};
I would like to understand the usage of 'this' in this context within the braces to an object of a class.我想了解“ this”在上下文中在类对象中的用法。
A new way of initialization called brace-initialization was introduced in C++11 which makes the following possible: C ++ 11中引入了一种称为brace-initialization的新初始化方式,这使得以下操作成为可能:
int z{ 0 };
std::vector<int> v{ 1, 3, 5 };
Widget w1{10};
Widget w2{w1};
And it is also possible to use this
for initialization. 也可以使用
this
进行初始化。
From the standard 12.6.2/7 "Initializing bases and members" available here : 从标准12.6.2 / 7“初始化基础和成员”中可以找到 :
12.6.2 Initializing bases and members [class.base.init]
12.6.2初始化基础和成员[class.base.init]
........
7 Names in the expression-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified.7 mem-initializer的expression-list中的名称在为其指定了mem-initializer的构造函数的范围内进行评估。
[Example:[例:
class X {
int a;
int b;
int i;
int j;
public:
const int& r;
X(int i): r(a), b(i), i(i), j(this->i) {}
};
initializes
X::r
to refer toX::a
, initializesX::b
with the value of the constructor parameter i, initializesX::i
with the value of the constructor parameteri
, and initializesX::j
with the value ofX::i
;初始化
X::r
指X::a
,初始化X::b
与构造参数i的值,初始化X::i
用构造参数的值i
,并初始化X::j
与值的X::i
; this takes place each time an object of class X is created.每次创建X类对象时都会发生这种情况。 ]
]
[Note: because the mem-initializer are evaluated in the scope of the constructor, thethis
pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized .[注意:由于mem-initializer在构造函数的范围内进行评估,因此可以在mem-initializer的expression-list中使用
this
指针来引用要初始化的对象 。 ]]
It's safe to use this
pointer in initialization-list as long as it's not being used to access uninitialized members or virtual functions. 只要不用于访问未初始化的成员或虚函数,可以在初始化列表中使用
this
指针是安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.