Reputation: 775
Here's my header file with the array Data
that my teacher wants to initialize in Heap
's constructor.
#ifndef HEAP_H
#define HEAP_H
class Heap
{
private:
int Data [100];
int Parent(int);
int RightChild(int);
int LeftChild(int);
void Heapify(int*, int);
void BuildHeap(int*);
public:
Heap();
void insert(int*);
void HeapSort(int*);
void ExtractMaximum(int*);
int Maximum(int*);
void PrintHeap(int*);
int heapsize;
int* GetData();
};
#endif
The Constructor is here:
Heap::Heap()
{
Data = {4, 12, 3, 19, 23, 5, 32, 11, 2, 24};
heapsize = 10;
BuildHeap(Data); //build a heap with initial values
}
Whenever I run the code with the first line of code in the constructor, initializing the array, I get the following warning:
Warning: extended initializer lists only available with
-std=c++0x
or-std=gnu++0x
Clearly I'm doing something wrong, and this is the only error/warning I have with this code, and it runs when I take away the line of code initializing Data
.
Upvotes: 2
Views: 1218
Reputation: 16726
Take a look here: http://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists
This is OK, the warning just tells you that you are using a new C++ feature but the compiler was not told so at the command line. The compiler wants you to tell him on the command line (with -std=c++0x
) that your code is written along the new C++ standard.
Upvotes: 0
Reputation: 62975
If you're limited to using C++03, then I would take this approach:
#include <algorithm>
Heap::Heap()
: Data() // value-initialize Data so initial elements are 0 instead of random
, heapsize(10) // initialize here instead of constructor body for consistency
{
static int const initData[] = { 4, 12, 3, 19, 23, 5, 32, 11, 2, 24 };
std::copy(initData, initData + sizeof(initData) / sizeof(initData[0]), Data);
BuildHeap(Data); //build a heap with initial values
}
If you are allowed to use C++11 functionality, then what you have is more or less fine, you just need to actually inform your compiler that you intend to use C++11 functionality (-std=c++0x
).
Upvotes: 2
Reputation: 308111
You're trying to assign an initializer list to the variable at a time after it has been created. As noted by the error message, this was not allowed until recent changes to C++ were ratified only a short time ago, probably well after your compiler was created.
It's doubtful that you really want to have a canned bunch of data built into your class. The more usual approach would be to pass the data as parameters into the constructor. The code that creates the object would have an array that is initialized as in your example, and pass that array into the constructor. The constructor would make a copy.
Upvotes: 0