此代码在GCC 4.9和Clang 3.5(带有标志-std = c 14)中编译并运行良好,但在VC 2015中给出了编译错误 . 请注意 operator*
中的自动返回类型:
#include <cstdio>
struct A {
int i;
constexpr A() : i(0) {};
constexpr A(int i) : i(i) {};
constexpr auto operator* (const A &a) const
{
return A(i * a.i);
}
};
int main()
{
constexpr auto b = A(100) * A(200);
printf("%d", b.i);
return 0;
}
main.cpp(67):错误C2127:'b':使用非常量表达式非法初始化'constexpr'实体
但如果我用 A
替换 auto
,它编译得很好:
#include <cstdio>
struct A {
int i;
constexpr A() : i(0) {};
constexpr A(int i) : i(i) {};
constexpr A operator* (const A &a) const
{
return A(i * a.i);
}
};
int main()
{
constexpr auto b = A(100) * A(200);
printf("%d", b.i);
return 0;
}
输出:20000
是什么赋予了?