简体   繁体   English

C ++实例变量/指向堆中数组的指针

[英]C++ Instance variable/pointer to an array in the heap

I have an dynamic array of structures. 我有一个动态的结构数组。 When I say dynamic, I mean that the number of elements can vary from each time the program is ran. 当我说动态时,我的意思是每次运行程序时元素的数量可以有所不同。 After having difficulty trying to use the instance variable as an array, I've been having incompatible types problems. 在尝试将实例变量用作数组遇到困难之后,我遇到了类型不兼容的问题。 Is there any other methods? 还有其他方法吗?

I have this structure: 我有这个结构:

struct movie
  {
    int rank;
    string title;
    string distributor;
    string weekend;
    string total;  
} ;

I have this class header file : 我有这个类头文件:

class ReadFile{

public:
    ifstream moviesFile;
    movie movies[];  

    ReadFile(string);
    movie handleLine(string);
    string getString(vector<char>);

};

This is how I'm trying to instantiate the movies instance variable: 这就是我尝试实例化movie实例变量的方式:

//Some code
movie temparray[linecount];
//temparray is filled with various movie structures.
movies = temparray;

This is when I get my error. 这是我收到错误消息的时间。 How would I accomplish my task of instantiating my movies array. 我将如何完成实例化我的电影数组的任务。 Thankyou! 谢谢!

Arrays are non-modifiable lvalues so you cannot assign to them 数组是不可修改的左值,因此无法分配给它们

So movies = temparray; movies = temparray; is illegal 是非法的

In C++ it is always recommended that you use a std::vector instead to C-style arrays 在C ++中,始终建议您使用std::vector而不是C样式数组

//....
public:
    ifstream moviesFile;
    std::vector<movie> movies;  

//....

//Some code
 movie temparray[linecount];
 movies.assign(temparray, temparray+linecount);

You can not define arrays of unknown size in C++, use std::vector<movie> movies; 您不能在C ++中定义未知大小的数组,请使用std::vector<movie> movies; to create a dynamic array. 创建一个动态数组。

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

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