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

标签 c++ arrays parameters 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 中带括号的初始值设定项”。 这是为了完成一个学校项目,不允许使用 vector (因为我发现做我的研究是明智的)尽管我想不出除了上面显示的方法之外的任何其他方法......

最佳答案

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

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

关于c++ - 如何在 C++ 中创建参数化对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745197/

相关文章:

C++ Redistributable 2012 更新 3 检测

c++ - 将 Visual C++ 项目迁移到 Visual Studio 2013 - DirectShow 基类错误 C2169

javascript - $.post 总是将空值传入服务器

ruby - 我可以在 Ruby 1.9.x 中使用无参数函数吗?

MySQL : When stored procedure parameter name is the same as table column name

c++ - 有没有办法为 C++03 实现 auto 关键字

c++ - 派生类构造函数中的异常

arrays - Numpy 中的分块操作

php - 按子数组排序数组

php - 基于 URL 参数选择的下拉列表 - PHP 或 jQuery?