如果参数中未传递任何值,如何创建具有默认值的对象
How do I create an object with a default value if none is passed in the parameter?
我正在尝试创建一个表,如果没有值传递给构造函数,该表的默认大小将为500。
示例
Table object; //sets table size to 500 by default
Table object(10000); //sets table size to 10000
这就是我目前设置标题的方式:
Class Table{
public:
Table();
//other functions excluded
private:
static const int tableSize = 500;
std::vector<int> A[tableSize];
};
我该怎么做?
这很可能是您想要的,假设您想要一个表,而不仅仅是一个序列。您的代码没有提到该表中每个行的大小,所以我使用您的代码:
class Table
{
public:
Table(size_t n = tableSize) : A(n) {};
//other functions excluded
private:
static const size_t tableSize = 500;
std::vector< std::vector<int> > A;
};
如果行缓冲区的大小是固定的(比如说100列),则可以使用std::array<>
作为行缓冲区,因此:
class Table
{
public:
Table(size_t n = tableSize) : A(n) {};
//other functions excluded
private:
static const size_t tableSize = 500;
std::vector< std::array<int,100> > A;
};
EDIT:增加哈希表
从注释中可以看出,这是为了提供一个哈希表实现,在这样做的过程中,需要扩展哈希表(这可能是最初的原因之一)。在这种情况下,您可以通过与第一个片段结合使用来直接扩展原始代码:
void Table::expand()
{
size_t new_size = 2*A.size() + 1;
std::vector< std::vector<int>> tmp(new_size);
for (auto& x : A)
{
std::hash<int> hfn;
for (auto y : x)
tmp[hfn(y) % new_size].push_back(y);
}
std::swap(A,tmp);
}
或者类似的东西。您的散列函数显然需要适当的集成,并且可能需要一个可选的大小因子等,但您有望得到这个想法。
你可以这样做:
Class Table{
public:
Table(int size = 500): A(size) { }
private:
std::vector<int> A;
};
(请注意,为了简洁起见,它是这样显示的。您可以/应该将接口与其实现分离,并在源文件中定义Table::Table
,初始化器列表也应该随之而来。)
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象