简体   繁体   English

C ++错误:数组初始化程序必须是初始化程序列表

[英]c++ error: array initializer must be an initializer list

I have really been struggling with a piece of code for a couple days. 几天来,我确实一直在努力编写一段代码。 The error message i receive when i run my code is: error: array initializer must be an initializer list accountStore (int size = 0) : accts(size) { } 运行代码时收到的错误消息是: error: array initializer must be an initializer list accountStore (int size = 0) : accts(size) { }

There seem to be others with similar problems here but unfortunately I am unable to apply their solutions (either don't work or not applicable). 这里似乎还有其他人遇到类似的问题,但是不幸的是,我无法应用他们的解决方案(无效或不适用)。

What I am simply attempting to do is create a container class (array, can't use vectors) of a class 'prepaidAccount' but I am just unable to get the constructor portion of the container class 'storeAccount' to work. 我只是试图做的是创建一个类“ prepaidAccount”的容器类(数组,不能使用向量),但是我只是无法使容器类“ storeAccount”的构造函数部分起作用。 See code snippet below: 请参见下面的代码段:

    class prepaidAccount{
public:
    //prepaidAccount ();
    prepaidAccount(string newPhoneNum, float newAvailBal) : phoneNumber(newPhoneNum), availableBalance (newAvailBal){} //constructor 

    double addBalance(double howMuch) {
        availableBalance = howMuch + availableBalance;
        return availableBalance;
    }
    double payForCall(int callDuration, double tariff) {
        callDuration = callDuration/60;     //convert to minutes
        double costOfCall = callDuration * tariff;
        if (costOfCall > availableBalance) {
            return -1;
        }
        else {
            availableBalance = availableBalance - costOfCall;
            return costOfCall;
        }
    }

    void setAvailBal(int newAvailBal) {availableBalance = newAvailBal;}
    float getAvailBal() {return availableBalance;}
    void setPhoneNum(string newPhoneNum) {phoneNumber = newPhoneNum;}
    string getPhoneNum() const {return phoneNumber;}
private:
    string phoneNumber;
    float availableBalance;
};

    class accountStore { //made to store 100 prepaid accounts
        public:
               accountStore (int size = 0) : accts(size) { }
                  ....
        private:
              prepaidAccount accts[100]; 
}

In main I simply call accountStore Account; 首先,我简单地称accountStore Account;

Any help is absolutely welcome. 任何帮助都是绝对欢迎的。 I very recently started learning c++ and about classes and constructors so please bear with me. 我最近开始学习c ++以及有关类和构造函数的知识,请耐心等待。

Thanks 谢谢

  1. You can't initialize an array with int like accountStore (int size = 0) : accts(size) {} . 您无法使用诸如accountStore (int size = 0) : accts(size) {}类的int初始化数组。

  2. prepaidAccount doesn't have a default constructor, you have to write member initialization list like, prepaidAccount没有默认的构造函数,您必须编写成员初始化列表,例如

    accountStore (int size = 0) : accts{prepaidAccount(...), prepaidAccount(...), ...} { }

The array has 100 elements, it's not a practical solution here. 该数组有100个元素,在这里不是实际的解决方案。

As a suggestion, think about std::vector , which has a constructor constructing with the spicified count of elements with specified value. 作为建议,考虑一下std::vector ,它具有一个构造函数,该构造函数使用指定值的元素的特殊计数构造。 Such as, 如,

class accountStore {
    public:
        accountStore (int size = 0) : accts(size, prepaidAccount(...)) { }
              ....
    private:
        std::vector<prepaidAccount> accts; 
};

Given that you have specified that you do not want to use a container such as std::vector but would like to specify the size at runtime, your only option would be to manually implement dynamic allocation yourself. 假设您已指定不想使用诸如std :: vector之类的容器,但想在运行时指定大小,则唯一的选择就是自己手动实现动态分配。 Also given that you are wanting create 100 objects at a time, I would suggest making a function that can construct a temporary object according to your needs and then use this to initialise your dynamically allocated array. 此外,考虑到您希望一次创建100个对象,我建议您创建一个可以根据需要构造一个临时对象的函数,然后使用该函数初始化动态分配的数组。 Consider the below code as a good starting point. 将以下代码视为一个良好的起点。 (WARNING untested code.) (警告未经测试的代码。)

class prepaidAccount {
 public:
  // Constructor
  prepaidAccount(string newPhoneNum, float newAvailBal)
      : phoneNumber(newPhoneNum), availableBalance(newAvailBal) {}
  // Default Constructor needed for dynamic allocation.
  prepaidAccount() {}

  /* your code*/
};

// Used to construct a tempoary prepaid account for copying to the array.
// Could use whatever constructor you see fit.
prepaidAccount MakePrepaidAccount(/*some parameters*/) {
  /* Some code to generate account */
  return some_var;
}

class accountStore {
 public:
  // Explicit constructor to avoid implicit type-casts.
  explicit accountStore(const int &size = 0)
      : accts(new prepaidAccount[size]) {
    for (int i = 0; i < size; i++) {
      // Will call defualt assignment function.
      prepaidAccount[i] = MakePrepaidAccount(/*some parameters*/);
    }
  }

  // Destructor
  ~accountStore() {
    // Cleans up dynamically allocated memory.
    delete[] prepaidAccount;
  }

  prepaidAccount *accts;
};

Edit: Amongst the c++ community it is often questionable when choosing to use dynamic allocation when there is such an excellent and comprehensive library of smart pointers. 编辑:在c ++社区中,当有如此出色而全面的智能指针库选择使用动态分配时,通常会遇到问题。 For example an std::vector would be perfect in this situation. 例如,在这种情况下, std::vector将是完美的。

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

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