如何将变量内容常量用作std :: array的大小? [英] How to turn a variable content constant for use it as the size of std::array?

查看:73
本文介绍了如何将变量内容常量用作std :: array的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属于该类的size变量.我想将其用作std :: array的大小,但我无法做到这一点.我找到了一些有关constexpr的文章,但到目前为止没有任何用处.你能帮我吗?

I have a size variable that belongs to the class. I would like to use it as the size of a std::array, but I was not able to do this. I found some articles that mention constexpr, but nothing useful so far. Can you help me?

#include<array>
#include<iostream>

class MyClass{
private:
        int size; //variable I need to copy the content and make it constant.
        void calculateSize(int x){
                size = 2 * x;
        }

public:
        MyClass(){}

        void createArray(int val){

                calculateSize(val);
                std::cout << "the size is: " << size << std::endl;
                std::array<int, size> myArray; // error
        }
};

int main(){

        MyClass c;
        c.createArray(5);
        return 0;
}

错误:

main.cpp:在成员函数‘void MyClass :: createArray(int)’中:main.cpp:20:19:错误:在常量表达式中使用"this"std :: array myArray;

main.cpp: In member function ‘void MyClass::createArray(int)’: main.cpp:20:19: error: use of ‘this’ in a constant expression std::array myArray;

推荐答案

这里的问题是对常量含义的误解.在C ++中,std :: array的大小必须为常量,其中常量表示在编译时已知大小".正如您的班级建议的那样, size 变量是在运行时计算的.同样, constexpr 关键字只能用于其值在编译时已知且永远不会更改的变量.

The problem here is a misunderstanding of what constant means. In C++, std::array's must be of constant size, where constant means "the size is known at compile-time." As your class suggests, the size variable is calculated at runtime. Likewise, the constexpr keyword can only be used for a variable whose value is known at compile time and will not ever change.

所以您有两种选择.

  1. 您可以使用 std :: vector 并将其初始化为大小

std::vector<int> vec(5); // Initializes a vector of size 5

  • 如果您确实在编译时知道数组的大小,则可以使用constexpr

  • If you really do know the size of the array at compile time, you can use constexpr

    constexpr int size = 2 * 10;
    std::array<int, size> arr; // Make an array of size 20
    

  • 这篇关于如何将变量内容常量用作std :: array的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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