c++ - 链成员初始值设定项

标签 c++

是否可以在“类初始化程序”中引用类成员?

示例:

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:

  1. 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/

相关文章:

c++ - 右值引用上的 std::vector<T>::emplace_back

c++ - 当通过引用访问时,Constexpr 成员函数返回不被视为 constexpr 的模板参数

c++ - 通过引用传递 char 数组

C++ MFC如何绘制Alpha透明矩形

c++ - scanf() 奇怪的行为!

c++ - 如何使用 enable_if 有条件地定义 << 运算符

c++ - C++ 11 中的数组

c++ - 如何保存 1 BPP、4 BPP 和 8BPP 图像

c++ - 傅里叶域去模糊算法

c++ - 将指向成员函数的指针与 std::shared_ptr 一起使用