【问题标题】:Default Constructor when creating an Array of Objects within an Object在对象中创建对象数组时的默认构造函数
【发布时间】:2017-08-21 16:42:45
【问题描述】:

我试图在另一个对象中创建一个对象数组(特别是在Checkbook 中的Check 数组。我不允许使用向量代替动态数组来存储对象,这令人抓狂,但这些都是我规定的规则。

我正在努力解决的问题是我需要为check 构造函数提供几个变量,因为它需要在check 对象中构造一个Money 对象。 所以我收到一条错误消息,声称 Check* checkArray = new Check[]; 没有默认构造函数。

我已经添加了一个默认构造函数,它只是 Check::Check() {};,但是如何在创建时不将参数最初传递给构造函数的情况下动态填充数组呢?我对 OOP 非常陌生,并且正在努力管理班级内的班级。 注意:money 类是预定义和实现的

这些相关支票的数据以 int(check number) '\t' double(check amount) '\t' int(bool for cashed 以 0 或 1 表示) 的形式存储在 .txt 文件中,并且我将数据临时存储在struct DataTransferStruct 中,然后将结构存储在向量中以进行测试,但我不能在最终实现中使用向量。我是不是在处理这个问题?

相关代码如下:

class Money
{
    private:
        long all_cents;

    public:
        friend Money operator +(const Money& amount1, const Money& amount2); //Returns sum of the values of amount1 and amount2
        friend Money operator -(const Money& amount1, const Money& amount2); //Returns amount1 minus amount2
        friend Money operator -(const Money& amount); //Returns the negative of the value of amount
        friend bool operator ==(const Money& amount1, const Money& amount2); //Returns true if amount1 and amount2 have the same value; false otherwise
        friend bool operator <(const Money& amount1, const Money& amount2) { return (amount1.all_cents < amount2.all_cents); }; //Returns true if amount1 is less than amount2; false otherwise

        Money(long dollars, int cents); // Initializes the object so its value represents an amount with the dollars and cents given by arguments.  If the amount is 
        //negative, then both dollars and cents should be negative

        Money::Money(long dollars) : all_cents(dollars * 100) {} //Initializes the object so its value represents $dollars.00

        Money::Money() : all_cents(0) {}//Initializes the object so its value represnets $0.00

        double get_value() const; //Returns the amount of money recorded in the data portion of hte calling object
};

检查类

class Check
{
    //Check dataTypes
    private:
        int checkNum;
        Money checkAmount;
        bool cashed;

    public:
        //Constructor
        Check::Check(long dollar_Value, int cents_Value, int check_Num, int cashed_) : checkAmount(CreateMoneyClass(dollar_Value, cents_Value)) { checkNum = check_Num; if (cashed_ == 1)cashed = true; else cashed = false; };
        Check::Check() {};
        //Deconstructor
        Check::~Check() {};

        //Member functions
        Money CreateMoneyClass(long dollar_Value, int cents_Value);
        int GetCheckNum() const { return checkNum; };
        double GetCheckAmount() const { return checkAmount.get_value(); };
        bool CheckCashed() const { return cashed; };

};

Money Check::CreateMoneyClass(long dollar_Value, int cents_Value)
{
    //Function that creates a Money object and returns to checkAmount within Check class 
    Money temp(dollar_Value,cents_Value);

    return temp;
}

刚开始 CheckBook 课

class CheckBook
{
    //Checkbook contains an array of checks
    private:
        Check* checkArray = new Check[];

};

我用来存储信息的方法

NewFile_Open(newFile);

    //take in and format each data line w/ struct and then construct check in dynamic growing array
    while (newFile >> temp.checkID)
    {
        newFile >> temp.rawMoneyAmount;
        newFile >> temp.checkCashed;

        //set dollars = rawMoneyAmount which drops cents
        temp.dollars = temp.rawMoneyAmount;

        //Get cents as int
        temp.cents = (int)((temp.rawMoneyAmount - temp.dollars) * 100);
    }

【问题讨论】:

  • 选择一个“规则”不那么愚蠢的雇主?
  • @KerrekSB 哈哈不错
  • 那么,你必须自己重新实现std::vector。您需要分配适当大小和对齐的原始存储,然后根据需要使用placement-new 在其中构造您的对象。
  • @Quentin 我不允许使用矢量。我知道如何创建一个动态数组并相应地调整它的大小,但我不确定如何在类结构中做到这一点。
  • @StormsEdge 是的,这就是“重新实现std::vector”的意思:创建自己的版本。

标签: c++ arrays oop constructor


【解决方案1】:

你不应该在课堂上做这样的数组

class CheckBook
{
    //Checkbook contains an array of checks
    private:
        Check* checkArray = new Check[];

};

您应该在类 CheckBook 构造函数中定义它。

喜欢

class CheckBook
    {
        //Checkbook contains an array of checks
        private:
            Check* checkArray;
        Checkbook()
        {
         checkArray = new checkArray[size];
        }
    };

【讨论】:

    【解决方案2】:

    构建没有默认构造函数的对象数组的正确方法是使用placement new语法将数组的分配和对象的构造分开。

    Checkbook::CheckBook(int size) { // A Checkbook containing size Checks
        // first the allocation
        Check * checkArray = reinterpret_cast<Check *>(new char[size * sizeof(Check)]);
        // then the actual construction
        for (int i=0; i<size; i++) {
            int checkNum = ...; // compute a check number possibly depending on i
            //actual construction of checkArray[i]
            new(checkArray + i) Check(0., 0., checkNumber, false);
        }
    }
    

    【讨论】:

    • 使用 char 作为分配基础对对齐有什么影响?这不会导致结构单字节对齐从而失去性能吗?将一些空白空间转换为类型是一个不错的技巧,但是,甚至要避免任何类型的构造函数。然而,完全绕过对象的构造函数系统听起来你需要小心,因为它绕过了类型安全的检查和平衡。
    • @JasonLang:char(或字节)是这里的内存单位:所有对象(位域除外)都需要占用整数个字节。保证为任何对象类型正确分配分配的内存。并且构造函数系统不会被绕过,因为它是由放置 new 触发的(稍后)。真实的是,尝试在其分配和对象构造之间使用checkArray 确实会调用未定义行为。
    • 好吧,如果您要投射到更大的项目,最好强制对齐,以便对其进行优化
    • @JasonLang:标准要求 C++ 分配系统(以及 C malloc)返回分配的内存,该内存适合任何对象类型对齐。这就是为什么允许用不同类型的对象覆盖分配的内存的原因,这是通过 normal new 或 new[] 分配完成的。
    • 是的,但您分配为 char,然后重新解释指针。对于重新解释的类型,它不一定会正确对齐。当然它会起作用,但不一定有效。
    【解决方案3】:

    一个问题是您试图在类定义中初始化 checkArray 对象。这不是这样做的适当地方。相反,checkArray 类型应该只在此处声明,并在 CheckBook 的构造函数中初始化:

    class CheckBook
    {
        public:
            CheckBook()
             : checkArray(new Check[]) // still an error here!
            {}
        private:
            Check* checkArray;
    
    };
    

    然而,这仍然不正确,因为 C 数组是固定大小的,这是一个大问题:您需要提前知道大小并将其传递给构造函数:

    class CheckBook
    {
        public:
            CheckBook(unsigned int numChecks)
             : checkArray(new Check[numChecks])
            {}
        private:
            Check* checkArray;
    
    };
    

    您真的应该反对不允许std::vector 的短视要求,除非这是一个家庭作业问题。在这种情况下,数组可能不是要使用的正确容器。 (如果这是家庭作业,我不会说什么会更好)。

    【讨论】:

      【解决方案4】:

      我建议创建一个 Init 方法,并让所有构造函数和初始化都通过它。这样,如果您以后需要 CheckBooks 的默认构造函数(例如,您需要一个 CheckBooks 数组),那么转换它会更容易。

      class CheckBook
      {
      public:
          CheckBook(unsigned int numChecks) : checkArray(0), size(0)
          {
                 Init(numChecks);
          }
      
          void Init(int _size)
          {
                if(checkArray != 0) // if there's already a checkArray, replace it.
                {
                      delete [] checkArray;
                }
      
                size = _size;
                checkArray = new Check[size];
      
                // for completeness you'd want to check that checkArray is not null 
                // otherwise the memory allocation failed
      
                for(int i = 0; i < size; ++i)
                {
                     // do your per-check set-ups here
                }
          }
      
          ~CheckBook() // make sure to clean up the dynamic memory
          {
                delete [] checkArray;
          }
      private:
          Check* checkArray;
          int size;
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-22
        • 1970-01-01
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-01
        • 1970-01-01
        相关资源
        最近更新 更多