如何在 DIFFERENT Class 的私有成员中声明指向 Class 对象数组的指针?

How do I declare a pointer to an array of Class objects, within the private members of a DIFFERENT Class?

在所有其他解决方案中大量使用 vector 作为万能药,这在很大程度上加剧了我对这个问题的困扰。

让我先说明这个问题,我需要使用指针来解决这个问题,尽管它们可能很烦人。我可能不会使用矢量,因为我们的课程中没有涉及它 material。

我习惯用下面的格式来声明一个指向数组的指针。

int* numbers;
numbers= new int[10];

Bingo,我刚刚创建了一个包含十个可以存储整数的元素的数组。哇!

现在,我正在尝试创建一个指向对象数组的指针,但不仅仅是任何对象!

我有两个 class。一个称为帐户,另一个称为交易。在我的帐户 class 的私人成员中,我需要 "A pointer to an array of Transactions, used to keep track of all of the transactions made for that account" 为什么我要这样做?打败我,这些是我得到的说明,我只是从帐户私人会员部分复制粘贴它们。

我是这样尝试的:

    class Account
{

    private:
        static const int MAX_TRANS = 100;
        int mAcctType;
        int mNumTrans;
        double mAcctBal;
        std::string mAcctName;

    Transaction* transaction;
    transaction = new Transaction[MAX_TRANS];

    void allocate();
    void deallocate();
    void copy(const Account& account);
public: 
    static const int CHECKING = 0;
    static const int SAVINGS = 1;

我不明白我做错了什么,但我收到了几条错误消息。

本节第一个:

`   Transaction* transaction;
    transaction = new Transaction[MAX_TRANS];`

我在交易下方看到了红色的波浪线,这是我现在尝试实例化的指针,表示 "the declaration has no storage class or type specifier"。为什么它不是交易类型?

接下来我收到以下错误消息。

C2143   syntax error: missing ';' before '*'
C2238   unexpected token(s) preceding ';'   
C4430   missing type specifier - int assumed. Note: C++ does not support default-int    

这是我交易的完整代码class:

#ifndef TRANSACTION_H
#define TRANSACTION_H

#include"Account.h"
#include <iostream>
#include <string>

class Transaction
{
private:
    int mTransType;
    double mTransAmt;

public:
    static const int DEPOSIT = 1;
    static const int WITHDRAW = 0;
    Transaction();
    Transaction(int mTransType, double mTransAmt);
    int GetTransType() { return mTransType; };
    double GetTransAmt() { return mTransAmt; };
    friend std::ostream &operator<<(std::ostream& out, Transaction transaction);
};

#endif

我不明白为什么我们要这样做,我相信你们中的许多人觉得这很荒谬。

我只需要知道在不同 class 的私有成员中声明指向对象数组指针的正确语法。

All I need to know is the proper syntax for declaring a pointer to an array of objects within the private members of a different class.

老实说,我不知道是否存在这样的东西,"a pointer to an array"。这里:

Transaction* transaction;

transaction 是指向单个 Transaction 的指针。如果您希望它成为动态分配数组的第一个元素,那么这就是您的业务。你必须做所有的簿记:分配正确的大小,如果需要重新分配,遵守 rule of 3/5,最后但并非最不重要的是确保你没有泄漏内存。所有这一切都是一场噩梦,它很容易出错,除了折磨学生之外,手动完成所有这些没有实际用途(std::vector 或智能指针应该用于动态数组)。这可能看起来像分裂头发,但重要的是要认识到 transaction 确实指向单个对象,如果你需要更多,你就得靠自己了。

transaction = new Transaction[MAX_TRANS]; 的问题是您不能在函数外部的 class 声明中分配给成员。您可以使用构造函数来分配数组。但是,如果无论如何你总是分配一个固定大小的数组,那么首先就不需要动态分配:

class Account {
private:
    static const int MAX_TRANS = 100;
    Transaction transaction[MAX_TRANS];
    // ... more ...
}