sht*_*ken 1 c++ object declare
我有一个HashTable <Customer>作为另一个类的成员.
HashTable <T>的构造函数采用int值来确定HashTable数组的大小.
HashTable(int numItems) { ... } //constructor
Run Code Online (Sandbox Code Playgroud)
以下声明
HashTable<Customer> customers(10000); //doesn't call constructor???
Run Code Online (Sandbox Code Playgroud)
收到10000下面的"预期的类型说明符"错误.当我删除10000时,我收到错误"找不到客户的函数定义".这让我相信编译器将我的对象声明视为函数声明.
当我使用动态分配声明我的HashTable时,
HashTable<Customer> * customers = new HashTable<Customer>(10000); //works
Run Code Online (Sandbox Code Playgroud)
与编译器没有混淆.
为什么动态分配工作,而不是其他?
编辑:这是一个具有上述相同问题的最小代码.
#ifndef _BUSINESS_LOGIC
#define _BUSINESS_LOGIC
#include "HashTable.h"
class BusinessLogic
{
public:
BusinessLogic();
~BusinessLogic();
void start();
private:
HashTable<int> * custom = new HashTable<int>(10000); //works
HashTable<int> customers(10000); //error
};
#endif
#ifndef _HASH_TABLE
#define _HASH_TABLE
template<class T>
class HashTable
{
public:
HashTable(int numItems) {
if (numItems <= 0) {
throw std::invalid_argument("Invalid HashTable size");
}
currItems = 0;
//B must be the next prime after 2 * numItems
B = numItems;
}
~HashTable() {
}
private:
int B; //size of itemArray
};
#endif
Run Code Online (Sandbox Code Playgroud)
()
在类定义中直接为类成员提供初始化程序时,不允许使用初始化程序语法.它需要-enclosed初始化程序的=
语法{}
.在你的情况下,它将是
HashTable<int> customers{10000};
Run Code Online (Sandbox Code Playgroud)
要么
HashTable<int> customers = 10000;
Run Code Online (Sandbox Code Playgroud)
或者,如果你愿意的话
HashTable<int> customers = { 10000 };
Run Code Online (Sandbox Code Playgroud)
最后两个版本有效,因为您的HashTable
专业化提供了适当的转换构造函数.如果声明了该构造函数explicit
,则必须使用
HashTable<int> customers = HashTable<int>(10000); // or `= HashTable<int>{10000}`
Run Code Online (Sandbox Code Playgroud)
代替第二和/或第三变体.
您尝试使用的初始化程序实际上正式称为括号或等于初始化程序.该名称暗示了语法的正确变体.
归档时间: |
|
查看次数: |
828 次 |
最近记录: |