是否可以在“类初始化程序”中引用类成员?
示例:
struct Example
{
std::string a = "Hello";
std::string b = a + "World";
};
它似乎可以工作(编译并运行),但是可以吗?
最佳答案
默认初始值设定项允许这样做 since C++11 。向下滚动到“用法”部分并查看第一个示例。我在这里复制了解释和示例以方便引用:
The name of a non-static data member or a non-static member function can only appear in the following three situations:
- As a part of class member access expression, in which the class either has this member or is derived from a class that has this member, including the implicit this-> member access expressions that appear when a non-static member name is used in any of the contexts where this is allowed (inside member function bodies, in member initializer lists, in the in-class default member initializers).
struct S
{
int m;
int n;
int x = m; // OK: implicit this-> allowed in default initializers (C++11)
S(int i) : m(i), n(m) // OK: implicit this-> allowed in member initializer lists
{
this->f(); // explicit member access expression
f(); // implicit this-> allowed in member function bodies
}
void f();
};
关于c++ - 链成员初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71340776/