How to Initialize an Array in the Constructor
May 21, 2010 at 7:00am UTC
I want to have an array as a class member, but the only way I know how to initialize the array in the constructor is by adding each element individually (array[x] = char).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <iostream>
using namespace std;
class MyClass
{
public :
MyClass();
~MyClass();
void PrintLetters(); // Prints each character in the array
private :
char alpha[3]; // Allocate memory for array
};
MyClass::MyClass()
{
// Initialize the array
alpha[0] = 'A' ;
alpha[1] = 'B' ;
alpha[2] = 'C' ;
PrintLetters();
}
MyClass::~MyClass()
{
}
void MyClass::PrintLetters()
{
for (int x = 0; x < 3; x += 1)
{
cout << alpha[x] << endl;
}
}
int main()
{
MyClass abc;
abc;
return 0;
}
Is there another way to do it? If I try to do it like this:
1 2 3 4 5 6 7
MyClass::MyClass()
{
// Initialize the array
alpha[3] = {'A' , 'B' , 'C' };
PrintLetters();
}
I get the following error:
$ g++ test.cpp -o test
test.cpp: In constructor ‘MyClass::MyClass()’:
test.cpp:17: error: expected primary-expression before ‘{’ token
test.cpp:17: error: expected `;' before ‘{’ token
The reason I ask is because I want an array with many more elements than three.
Last edited on May 21, 2010 at 7:26am UTC
May 21, 2010 at 7:35am UTC
I figured out what I wanted to do using a "for" loop:
1 2 3 4 5
string letters = "ABC" ;
for (int x = 0; x < sizeof (alpha); x +=1)
{
alpha[x] = letters[x];
}
Last edited on May 21, 2010 at 7:35am UTC
May 21, 2010 at 9:48am UTC
Why not use string?
Topic archived. No new replies allowed.