gpt4 book ai didi

c++ - 将大括号内的 'this' 传递给 C++ 中的类的对象

转载 作者:搜寻专家 更新时间:2023-10-31 00:52:22 24 4
gpt4 key购买 nike

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};
};

我无法理解这篇文章中最后一行的用法。有人可以解释一下这里发生了什么吗?

行:区域对象{this};

我想了解 this 在大括号内对类对象的用法。

最佳答案

Line: District object{this};
I would like to understand the usage of 'this' in this context within the braces to an object of a class.

在 C++11 中引入了一种称为大括号初始化的新初始化方法,它使以下成为可能:

int z{ 0 }; 
std::vector<int> v{ 1, 3, 5 };
Widget w1{10};
Widget w2{w1};

而且也可以使用this进行初始化。

来自标准 12.6.2/7“初始化基和成员”可用 here :

12.6.2 Initializing bases and members [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.
[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 to X::a, initializes X::b with the value of the constructor parameter i, initializes X::i with the value of the constructor parameter i, and initializes X::j with the value of X::i; this takes place each time an object of class X is created. ]
[Note: because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized. ]

在初始化列表中使用 this 指针是安全的,只要它不被用于访问未初始化的成员或虚函数。

关于c++ - 将大括号内的 'this' 传递给 C++ 中的类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51942748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com