为什么班级成员的顺序很重要?

时间:2014-07-08 03:06:15

标签: c++ class member auto decltype

我的编译器是GCC 4.9.0。

struct A {

    int n;

    auto f() -> decltype(n) { // OK
        return n;
    }
};

struct B {

    auto f() -> decltype(n) { // error: 'n' was not declared in this scope
        return n;
    }

    int n;
};

int main() {

    return A().f() + B().f();
}

为什么班级成员的顺序很重要?

1 个答案:

答案 0 :(得分:3)

声明按顺序编译。这是你不能写的原因:

int y = x;
int x = 5;

内联函数的主体(包括c-tor初始化列表)将在稍后处理(当然首先解析,但直到类定义完成后才查找名称),因此它们可以引用类成员在以后的行。

相关问题