为什么这个程序在 C++14 中编译得很好,但在 C++11 编译器中却不行?

Why does this program compile fine in C++14 but not in a C++11 compiler?

我最近在在线编译器上测试了下面这个简单的程序。查看现场演示 here。它编译得很好并给出了预期的输出,但是当我在 Dev C++ IDE 上测试它时,它在编译过程中失败了。

这是我的程序:

#include <iostream>
class Test
{
    int s=9;
    public:
    int get_s()
    {
        return s;
    }
};
int main()
{
    Test s;
    Test& t{s};      // error in C++11 but not in C++14 why???
    std::cout<<t.get_s();
} 

它给我以下错误:

[Error] invalid initialization of non-const reference of type 'Test&' from an rvalue of type '<brace-enclosed initializer list>'

我还在代码块 13.12 IDE 上尝试过,它给我的错误与 Dev C++ 给出的错误相同。

这是 C++14 的新功能吗?为什么它不能在 C++11 编译器中工作?

它适用于 C++14 和 works on C++11。您很可能使用了过时的编译器。

针对您的确切问题(参见 DR 1288)有一个已修复的错误 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=50025)

C++0x initialization syntax doesn't work for class members of reference type

引用自Jonathan Wakely

The original C++11 rules required a temporary to be created there and the reference member binds to that temporary.

来源:Defect Report 1288

它适用于所有这些编译器的 c++11c++14

gcc 4.9.2
gcc 5.1.0
clang 3.5.0

很可能您使用的是旧版本的 gcc 或其他尚未实现此 c++11 功能的编译器。

c++11 是由编译器分阶段实现的。每个版本 added/improved/fix 一些 c++11 特性。