创建结构数组

时间:2014-01-29 16:01:23

标签: c++ arrays class

我正在尝试创建一个结构数组,但我收到错误no matching function for call to 'Cell::Cell()'

Cell是我的结构的名称。以下是我的一些代码:

struct Cell{
    int number;

    Cell(int n){
        number = n;
    }
};

class MyClass{
    public:
        int nCells;

        void inject(){
            std::cout << "Enter number:";
            string in;
            std::cin >> in;
            int amount = in.size()/3;

            Cell cells [amount]; // <-- error

            int index = 0;
            int t = in.size();
            while (t >= 3){
                cells[index] = new Cell(atoi(in.substr(t-3,3).c_str());
                t -= 3;
                index++;
            }
        }

        MyClass(int n){
            nCells = n;
        }
};

Cell cells [amount];给了我错误。我是新手,但我知道如何制作基本类型的数组。例如,int cells [amount];会起作用。

但我怎么做一个Cell类型的数组呢?

3 个答案:

答案 0 :(得分:4)

Cell没有默认构造函数(只要指定另一个构造函数,编译器就不会再创建默认构造函数)。但是,定义Cell cells[amount]将自动默认初始化每个元素。

我认为在这种特殊情况下最好的方法就是实现默认构造函数:

struct Cell{
    int number;

    Cell() : number(0)
    {
    }

    Cell(int n) : number(n)
    {
    }
};

另请注意,由于amount在编译时未知,Cell cells[amount]基本上是非法的。但是有些编译器有扩展功能允许这样做。但如果你堆分配它会更好:

Cell* cells = new Cell[amount];

不要忘记销毁它。

答案 1 :(得分:2)

如果知道数组有多长,可以使用c ++ 11初始化。这样做:

int main()
{
    Cell c[3]{ Cell(1), Cell(2), Cell(3) };
}

顺便说一句

Cell cells [amount];

正在使用VLA,c ++不支持(仅作为某些编译器的扩展)。

在c ++中,更好的方法是使用std::vector

#include <vector>


struct Cell{
    int number;

    Cell(int n){
        number = n;
    }
};

int main()
{
    int n = 5;

    std::vector< Cell > c;

    for ( int i =0; i < n; ++ i )
    {
        c.emplace_back( Cell( i ) );
    }
}

答案 2 :(得分:0)

通过执行Cell cells [amount];,您正在调用Cell构造函数,但在这种情况下,您没有Cell的默认构造函数,因此您必须使用指针,而不是他们在while的东西。

只需更改

Cell cells [amount];

Cell* cells [amount];