如何在一个类中初始化和使用另一个类的数组?(c++)

How to initialize and use an array of another class in a class? (C++)

本文关键字:另一个 c++ 数组 一个 初始化      更新时间:2023-10-16

所以我是c++的新手,在Java中,很容易使用其他类的数组,我想知道是否有一种方法可以使用其他类的数组,如:

#include <iostream>
#include <array>
#include <string>
using namespace std;
class Message
{...}
class UserMessageFile
{
    private:
        Message[] messages;
}
int main(int argc, const char * argv[])
{
        return 0;
}

为什么我不能在我的UserMessageFile类中使用Message类的数组?在我能做到这一点之前,我需要在UserMessageFile类中包含Message类吗?我该如何做到这一点呢?

不能指定大小未知的数组作为类成员(实际上,除非它带有静态初始化器,否则不能指定大小未知的数组,并且不能在类定义中使用这些初始化器)。

您要找的是std::vector

class UserMessageFile
{
private:
    std::vector<Message> messages;
};

您几乎应该总是使用std::类型。所以用std::vectorstd::array。如果你真的需要使用c风格的数组,你必须这样做:

Messages messages[10]; // Your syntax must have the array 
                       // braces at the end and you must specify
                       // an array length.

下面是一个实例。

其他语法错误包括:

  1. 类必须以分号(class a {};)结尾。
  2. 不要在你的类中使用...,这是不识别的。
相关文章: