有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
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?
我有一个名为"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
时,这里固定大小的原因是什么?
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放