我今天编写了一些代码并得到了一个奇怪的编译错误,这似乎是由于成员变量的初始化顺序与声明的顺序不同.
例:
class Test {
int a;
int b;
public:
Test() : b(1), a(2) {
}
};
int main() {
Test test;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后,如果我编译它-Werror -Wall:
$ g++ -Werror -Wall test.cpp
test.cpp: In constructor ‘Test::Test()’:
test.cpp:3:9: error: ‘Test::b’ will be initialized after [-Werror=reorder]
test.cpp:2:9: error: ‘int Test::a’ [-Werror=reorder]
test.cpp:6:5: error: when initialized here [-Werror=reorder]
cc1plus: all warnings being treated as errors
Run Code Online (Sandbox Code Playgroud)
我意识到这-Wall是明确要求GCC过度警告,但我认为所有这些都是有原因的.那么,初始化成员变量的顺序怎么样呢?
我遇到了一个名为"member initializer"的奇怪概念.
这里说:
C++ 11添加了成员初始化器,如果构造函数没有初始化成员本身,则表达式将应用于类范围内的成员.
它的定义是什么?
是否有一些例子来说明它的用法?
我有一个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)