我遇到了这个C++问题:
问题:以下是定义或声明吗?
Foo f(Bar());
Run Code Online (Sandbox Code Playgroud)
答案:它可能是一个函数的声明,它接受类型Bar并返回类型Foo,或者它是f一个类型的定义Foo,它有一个类型为Bar的构造函数.问题是两者的语法是相同的,所以为了解决这个问题,C++标准规定编译器必须更喜欢函数声明,而不能对它进行区分.
- 我不明白为什么它可以是"一个函数的声明,它采用类型Bar并返回类型Foo"?如何在参数列表中出现括号"()"?
我有一个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 = …Run Code Online (Sandbox Code Playgroud)