为什么不能将静态constexpr成员变量传递给函数? [英] Why can't a static constexpr member variable be passed to a function?

查看:147
本文介绍了为什么不能将静态constexpr成员变量传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码生成对 Test :: color 的未定义引用。

The following code produces an undefined reference to 'Test::color'.

#include <iostream>

struct Color{
    int r,g,b;
};

void printColor(Color color) {
    //printing color
}

class Test {
    static constexpr Color color = {242,34,4};
public:
    void print(){
        printColor(color);
    }
};


int main() {
    Test test;
    test.print();

    return 0;
}

为什么此代码会产生上述错误,以及避免这种情况的最佳方法是什么考虑到我想使用标准的最新版本C ++ 17?

Why does this code produce the above error and what is the best way to avoid it, considering I want to use the latest version of the standard, C++17?

我应该定义静态成员变量,就像在早期版本中需要的一样标准(请参见此处的第一个答案:对静态constexpr char []的未定义引用)还是应该只创建一个新的 Color 结构,如下所示?

Should I define the static member variable, just like it was needed in earlier revisions of the standard (see the first answer here: Undefined reference to static constexpr char[]) or should I just create a new Color structure as can be seen below?

printColor(Color{color.r, color.g, color.b});

编辑:
我在Ubuntu 16.04上使用CLion,据我所知找出来,使用g ++ 5.4进行编译。我已将其设置为使用C ++ 17,但仍然收到相同的错误。仅当 color 传递给函数时,才会出现该错误。

I'm using CLion on Ubuntu 16.04, which as far as I could find out, uses g++ 5.4 for compiling. I have set it to use C++17 and still get the same error. The error is only present when color is passed to a function.

推荐答案

问题既不在于代码本身,也不在于所使用的标准。 CLion的默认编译器不完全支持C ++ 17,因此它表现出奇怪的行为,它可以编译 static constexpr 成员变量,但前提是它们不

The problem was neither with the code itself, nor with the standard being used. CLion's default compiler does not fully support C++17, so that's why it showed a strange behavior that it could compile static constexpr member variables, but only as long as they were not passed to functions.

更新到最新的编译器版本后,我能够成功运行代码,而无需进行任何更改。

After updating to the most recent compiler version, I was able to run the code successfully without any changes.

感谢您的所有贡献。

这篇关于为什么不能将静态constexpr成员变量传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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