如何在C ++中创建参数化对象数组?

时间:2017-12-11 01:09:03

标签: c++ arrays parameters constructor parameterized-constructor

 class book{
private:
    int numOfPages;
public:
    book(int i){
    numOfPages = i;
    };
};

class library{
private:
    book * arrOfBooks;
public:
    library(int x, int y){
        arrOfBooks = new book[x](y);
    };
};
int main()
{
  library(2, 4); 
};

通过上面的示例代码,我想创建一个所有页面数相同的图书库。因此,在库对象的构造函数中,每当创建要放入数组的新书时,我都会在括号中传递参数。 在C++ shell中测试时,上面的代码显示错误:"数组new"中带括号的初始值设定项。 这是为了完成一个学校项目,不允许任何载体(因为我发现做我的研究是明智的)虽然我想不出任何其他方法来做这个比上面显示的...

3 个答案:

答案 0 :(得分:0)

没有使用非默认构造函数初始化动态数组元素的语法。

您必须先创建数组,然后遍历元素并分别分配。可能最简单的方法是使用std::fill

答案 1 :(得分:0)

书籍数组是一维数组,应按如下方式定义:

library(int x)
{
        arrOfBooks = new book[x];
};

如果您假设所有图书都有相同的页面,则您将其作为默认参数传递给图书类构造函数:

book(int i=200)//set the defautlt value here
{
    numOfPages = i;
};

答案 2 :(得分:0)

使用模板:

#include <iostream>

template <int book_capacity> class book
{
private:
    int numOfPages;
public:
    book(): numOfPages(book_capacity){}
};

template <int lib_capacity, int book_capacity> class library 
{
private:
    book<book_capacity> arrOfBooks[lib_capacity];
    int cnt;
public:
    library(): cnt(0) {}
    void addBook(book<book_capacity> b)
    {
        if (cnt < lib_capacity)
        {
            arrOfBooks[cnt] = b;
            cnt++;
            std::cout << "book is added" << std::endl;
            return;
        }

        std::cout << "library is full" << std::endl;
    }
};

int main() 
{

    library<2, 4> lib;
    book<4> b;

    lib.addBook(b);
    lib.addBook(b);
    lib.addBook(b);
    lib.addBook(b);

    system("pause");
    return 0;
}

enter image description here