有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?

is there a way to initialize an array of objects that is inside of the private section of another class using the constructor of that class?

本文关键字:数组 对象 初始化 有没有 构造函数 另一个      更新时间:2023-10-16

我有一个名为"author"的类和另一个名为"book"的类,我想在类书的私有中有一个作者数组,我想在构造函数中初始化它。


#include<iostream>
#include<string>
using namespace std;
class author
{
string name;
string email;
public:
author(string name,string email):name{name},email{email}{}
...
};
class book
{
double price;
string name;
author writer[3];
public:
book(double price,string name,author writer[3]):price{price},name{name},writer[3]{writer[3]}{}
....
};
int main()
{
...
return 0;
}    

我收到此错误"调用"作者::作者(("没有匹配函数

这与构造函数无关,但与您尝试初始化 C 样式数组的方式有关。如果你想坚持使用 C 风格的数组,你需要显式复制所有元素:

book(double price,string name,author writer[3])
: price{price}
, name{name}
, writer{writer[0], writer[1], writer[2]}
{}

请注意,这是不安全的 - 编译器不检查数组的大小,因此它会编译您提供了两个元素的数组,但您将具有未定义的行为。也不能使用循环,除非author具有默认构造函数。

更合理的方法是使用std::vector- 它允许您拥有任意数量的作者,而不是每本书固定 3 个。

class book
{
double price;
string name;
std::vector<author> writer;
public:
book(double price,string name,std::vector<author> writer)
: price{price}
, name{name}
, writer{std::move(writer)}
{}
....
};

原始数组在 C 语言中不是第一类对象,它们也不是C++:您不能分配给数组,也不能直接从另一个数组初始化它。您只能分配给其单个元素,或从其他元素初始化它。

如果你真的想走这条路,你必须写:

book(double price,string name,author writer[3]):price{price},name{name},
writer{writer[0], writer[1], writer[2]}{}

出于这个原因,标准C++库提供了std::array,它只是一个围绕原始数组的微小包装器,但允许从另一个数组直接初始化或赋值。但是正如您在评论中被告知的那样,当您可以使用std::vector时,这里固定大小的原因是什么?