简体   繁体   English

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

[英]How to create an array of parameterized objects in C++?

 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); 
};

With the example code above I would like to create a library of books that all have the same number of pages. 在上面的示例代码中,我想创建一个书库,它们全部具有相同的页数。 So in the constructor of the library object, whenever a new book is created to be placed in the array I pass the argument in the parenthesis. 因此,在库对象的构造函数中,每当创建一本新书放置在数组中时,我都会在括号中传递参数。 The above code when tested in C++ shell shows error: "parenthesized initializer in array new". C ++ Shell中测试时,以上代码显示错误:“在new数组中用括号括起的初始化程序”。 This is for the completion of a school project and no vectors are allowed (as it would be wise to do as I found doing my research) though I cannot think of any other ways to do it than the one shown above... 这是为了完成一个学校项目,不允许使用任何载体(这是我进行研究时发现的明智之举),尽管除了上面显示的方法外,我没有其他方法可以想到...

There is no syntax for initializing elements of a dynamic array using a non-default constructor. 没有使用非默认构造函数初始化动态数组元素的语法。

You have to create the array first, then loop over the elements and assign each individually. 您必须先创建数组,然后循环遍历元素并分别分配每个元素。 Possibly the simplest way to do that is to use std::fill . 可能最简单的方法是使用std::fill

Array of books is a one dimensional array and it should be defined as follows: 书本数组是一维数组,应定义如下:

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

If you have an assumption all books have same page you have pass it as a default parameter to your book class constructor: 如果您假设所有书籍的页面都相同,则可以将其作为默认参数传递给书籍类构造函数:

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

Using templates: 使用模板:

#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;
}

在此处输入图片说明

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

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