c++ - 为什么编译器认为我的对象声明是函数声明?

标签 c++ object declare

<分区>

我有一个 HashTable< Customer > 作为另一个类的成员。

HashTable< T > 的构造函数采用 int 值以确定 HashTable 数组的大小。

HashTable(int numItems) { ... } //constructor

下面的声明

HashTable<Customer> customers(10000); //doesn't call constructor???

在 10000 下收到错误“需要类型说明符”。当我删除 10000 时,收到错误“找不到客户的函数定义”。这使我相信编译器将我的对象声明视为函数声明。

当我使用动态分配声明我的哈希表时,

HashTable<Customer> * customers = new HashTable<Customer>(10000); //works

与编译器没有混淆。

为什么动态分配起作用,而另一个不起作用?

编辑:这是具有上述相同问题的最小代码。

#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

最佳答案

在类定义中直接为类成员提供初始值设定项时,不允许使用 () 初始值设定项语法。它需要 = 语法或 {} 封闭的初始值设定项。在你的情况下,它要么是

HashTable<int> customers{10000};

HashTable<int> customers = 10000;

或者,如果你愿意的话

HashTable<int> customers = { 10000 };

最后两个版本之所以有效,是因为您的 HashTable 特化提供了适当的转换构造函数。如果该构造函数被声明为 explicit,则您必须使用

HashTable<int> customers = HashTable<int>(10000); // or `= HashTable<int>{10000}`

代替第二个和/或第三个变体。

您尝试使用的初始化程序实际上正式称为brace-or-equal-initializer。该名称暗示了语法的正确变体。

关于c++ - 为什么编译器认为我的对象声明是函数声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41114283/

相关文章:

c++ - 包含另一个类的对象的类的大小

c++ - 如何使用模板创建与另一个变量类型相同的变量?

java - 使用条件java删除重复的列表对象

javascript - nodejs将相同的变量传递给不同的模块

Javascript 使用 object.create() 从字符串构建一棵树

sql - 必须在子选择 SQL 中声明标量变量错误

angular - "declare global{ interface Window{ analytics: any; } }"在 angular/Typescript 中是什么意思?

c++ - 通过linux终端将数据发送到另一个进程的stdin

c++ - 快速中值更新算法

c++ - 'struct random_data* buf' 的类型是什么?