1
 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中测试时显示错误:“array new 中的带括号的初始化程序”。这是为了完成一个学校项目,不允许使用向量(因为我发现这样做是明智的)尽管我想不出除了上面显示的方法之外的任何其他方法......

4

3 回答 3

0

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

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

于 2017-12-11T01:19:26.423 回答
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;
}

在此处输入图像描述

于 2017-12-11T01:46:37.187 回答
0

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

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

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

book(int i=200)//set the defautlt value here
{
    numOfPages = i;
};
于 2017-12-11T01:33:08.313 回答