dodle
May 21st, 2010, 08:24 AM
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).
#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:
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.
#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:
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.