c++ - 在 constexpr : what does the standard say? 中使用非常量

标签 c++ c++11 standards-compliance constexpr

C++11 iso 标准对这样的表达式是怎么说的:

class MyClass
{
    public:
        constexpr int test()
        {
            return _x;
        }

    protected:
        int _x;
};

_xconstexpr 中使用的非常量:它会产生错误,还是会简单地忽略 constexpr(如当我们传递一个非常量参数时)?

最佳答案

非常好,虽然有点没用:

constexpr int n = MyClass().test();

因为 MyClass 是一个集合,像这样对它进行值初始化将对所有成员进行值初始化,所以它只是零。但经过一些润色,这可以变得真正有用​​:

class MyClass
{
public:
    constexpr MyClass() : _x(5) { }
    constexpr int test() { return _x; }
// ...
};

constexpr int n = MyClass().test();  // 5

关于c++ - 在 constexpr : what does the standard say? 中使用非常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12605552/

相关文章:

get 语句时 C++ 崩溃?

c++ - 如何在QTreeView的第二列添加项目

C++0x 静态初始化和线程安全

.net - 如何以符合标准的方式序列化 .NET 中的 DateTime 对象

swift - 协议(protocol)功能实现,实际上不符合协议(protocol)

c++ - Qt 序列化 - 如何排除一个字段?

C++:将 const 与 STL 迭代器一起使用

c++ - 在 C++11 中移出 std priority_queue 的元素

c++ - 将 1 位宽的位域设置为 2 是否意味着位域已设置或未设置?

objective-c - 如何为 Objective-C 协议(protocol)提供默认实现?