使用constexpr构造函数和函数(不同vc,g ++)的文字类编译错误 [英] literal class compile error with constexpr constructor and function (differ vc, g++)

查看:96
本文介绍了使用constexpr构造函数和函数(不同vc,g ++)的文字类编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
#include< string>
使用命名空间std;

A类{
public:
constexpr A(){}
constexpr int area(){
返回12;
}
private:
// constexpr int h = 3;
// constexpr int w = 4;
};
int main()
{
constexpr A a;
constexpr int j = a.area();
cout<< j<<恩德尔

}

为什么上面的代码不能同时使用MSVC编译器进行编译适用于g ++? MSVC是否不如其他编译器那么严格? MSVC和g ++之间的差异结果有时会令人困惑。


解决方案

问题是 constexpr 对象意味着 const ,这意味着您不能调用 area ,因为它是非const函数。将区域标记为 const 就是这样。



,使 a 为非常量将使您可以保留 area 为非常量,尽管这很奇怪,但它是有效的C ++。



编辑。也许您使用的是C ++ 14或更高版本。您的印象是 constexpr 函数暗示 const 是C ++ 11的一个功能,在以后的标准中已更改。


#include <iostream>
#include <string>
using namespace std;

class A {
public:
    constexpr A() {}
    constexpr int area() {
        return 12;
    }
private:
//  constexpr int h = 3;
//  constexpr int w = 4;
};
int main()
{
    constexpr A a;
    constexpr int j = a.area();
    cout << j << endl;

}

Why the code above can't compile with MSVC compiler while works with g++? Isn't MSVC not as strict as other compilers? The difference results between MSVC and g++ is sometimes confusing. Which compiler should I rely on, any tips btw?

解决方案

The problem is that a constexpr object implies const, which means you cannot call area as it is a non-const function. Mark area as const and that's it.

Alternatively, making a non-const will allow you to keep area non-const, which whilst odd, it's valid C++.

EDIT. Perhaps you are using C++14 or above. Your impression that a constexpr function implies const is a C++11 feature that was changed in later standards.

这篇关于使用constexpr构造函数和函数(不同vc,g ++)的文字类编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆