繁体   English   中英

我不知道如何编辑数组中的数据,有一次我在增加大小后“忘记”了数据。 (C++)

[英]I can't figure out how to edit the data in my array and the one time that I did it "forgot" the data after I increased the size. (C++)

我对 C++ 有点陌生 我决定做一个小项目,目前我正在尝试设置一些东西来制作一个数组,将 5 个对象放入其中,然后增加其大小并放入更多对象; 但是,我遇到了一个问题,我无法弄清楚如何将数据放入数组中

这是我到目前为止所得到的:

#include <iostream>
#include "Token.h"

int main()
{
    Token* ts = new Token[5]; //create the initial array
    ts[0] = new Token(TT_PLUS, "+"); //add the item

    int size = sizeof(ts) / sizeof(Token); //get the new size
    size_t newSize = size * 2; // double it
    Token* newArr = new Token[newSize]; //create new array

    memcpy(newArr, ts, size * sizeof(Token)); //copy data

    size = newSize; //The array resizing is code I found, so I'm not sure why this is here...
    delete[] ts; //delete old array data
    ts = newArr; // array is now updated?
    std::cout << ts[0].type << std::endl; trying to get the type of  Token 0
}

这是我的错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0349   no operator "=" matches these operands  ATestProgrammingLang    C:\Users\usr\source\repos\ATestProgrammingLang\ATestProgrammingLang.cpp 10
Severity    Code    Description Project File    Line    Suppression State
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'Token *' (or there is no acceptable conversion) ATestProgrammingLang    C:\Users\usr\source\repos\ATestProgrammingLang\ATestProgrammingLang.cpp 10  

如果我需要为您提供更多信息,请告诉我。

首先,我认为你使用 C 风格。 使用 STL 容器(例如 std::vector)而不是 c arrays。我不知道 Token class 是什么,但我认为您不需要在这部分使用 new:

ts[0] = new Token(TT_PLUS, "+"); //add the item

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM