【发布时间】:2020-11-27 12:41:09
【问题描述】:
我目前正在学习类和构造函数。
class Container
{
....
public:
// constructors
Container() {
length = 0;
data = nullptr;
print("default constructor");}
Container(int lenght){
data = new double[lenght];
}
// destructor
// operators
void print(const std::string& info) const
{
// print the address of this instance, the attributes `length` and
// `data` and the `info` string
std::cout << " " << this << " " << length << " " << data << " "
<< info << std::endl;
}
private:
int length;
double* data;
};
我已经做了两个构造函数。我需要制作一个额外的构造函数。我得到了以下指令。
创建一个接受 std::initializer_list 的构造函数。这 list 包含数据数组的值。使用构造函数委托 设置此容器的长度并分配数据。然后全部复制 将列表的元素转换为数据。
我在施工委托方面遇到了麻烦。因为如果新的构造函数接受一个参数。我需要委托长度的先前构造如何(因为唯一的输入变量是int)? 此外,我对数据的分配和复制感到困惑。
谁能给我一个例子来帮助我解决这个问题?
谢谢, 纳丁:)
【问题讨论】:
-
附带说明,构造函数委托似乎总是一个糟糕的选择,不是吗?
-
@OrenIshShalom 为什么这是一个糟糕的选择?
-
见stackoverflow.com/questions/26199431/… 和那里的讨论链接.. 我想这是一个品味问题......
标签: c++