为Structs C ++向量创建尺寸时出错 [英] Error creating a size for a vector of Structs C++

查看:59
本文介绍了为Structs C ++向量创建尺寸时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在上大学时正在做的一个项目,但找不到适合我的解决方案.我很可能不明白答案.

This is for a project I am doing for my college class and I could not find an answer for this that worked for me anywhere. Its very likely I did not understand the answers though.

我有一个结构体(menuItem),并将该结构体放入一个类(Menu)中.之前,我已经在Menu类中成功创建了一个struct menuItem数组,但是当我尝试在Menu内部创建一个menuItem的向量时,尝试初始化其大小时会出现此错误

I have a struct (menuItem), and that struct is put into a class (Menu). I have successfully created an array of struct menuItem inside class Menu before, but when I try to create a vector of menuItem inside Menu I get this error when I try to initialize its size

错误C2059:语法错误:恒定"

error C2059: syntax error : 'constant'

这是令人反感的代码:

#include <vector>

using namespace std;

//previous array value
const int MAXCOUNT = 20;

struct menuItem
{
    void(*func)();
    char description[50];
};

class Menu
{
private:
    std::vector<menuItem> mi(20); // <<< "The error occurs when I set the vector to a size of 20"
    int count;
    void runSelection();
};

当我将向量初始化为无尺寸时,不会出现此错误,但是当我使用 mi.resize(20); 时,它会再次以这种上下文错误的形式弹出:错误,这种减速没有存储类或类型说明符",这是没有意义的,因为根据我认为向量如何初始化,我将向量 mi 的类型设置为类型 menuItem

This error does not pup up when I initialize the vector as sizeless, but it pops up once again the second I use mi.resize(20); in the form of this contextual error: "Error, this deceleration has no storage class or type specifier", which makes no sense because I set the type of the vector mi as type menuItem per how I believe vectors are initialized.

我假设我以某种方式初始化向量错误,或者我将结构设置为错误.我发现答案"表明结构是没有我知道的私有部分的类,并且您必须有一个构造函数来初始化结构的向量,而我不知道.问题是,我没有想到的构造函数可以使错误消失.我完全迷路了,不胜感激.

I am assuming I am initializing the vector wrong somehow, or I am setting up the struct wrong. I've found "answers" stating that structs are classes without a private section which I knew, and that you have to have a constructor to initialize a vector of structs, which I did not know. Problem is, no constructor I've come up with has made the error go away. I am completely lost and would appreciate some assistance.

推荐答案

您可以在C ++ 11中像这样

You can do this in C++11 like so

class Menu
{
private:
    std::vector<menuItem> mi = std::vector<menuItem>(20);
};

或者如果您坚持使用C ++ 03,则需要在构造函数的初始值设定项列表中对其进行初始化

or if you are stuck using C++03 you will need to initialize it in the constructors initializer list

class Menu
{
public:
    Menu() : mi(20) {}

private:
    std::vector<menuItem> mi;
};

这篇关于为Structs C ++向量创建尺寸时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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