PDA

View Full Version : [SOLVED] [C++] How to Initialize an Array in the Constructor



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.

dodle
May 21st, 2010, 08:34 AM
I figured out what I wanted to do using a for loop:


string letters = "ABC";
for (int x = 0; x < sizeof(alpha); x +=1)
{
alpha[x] = letters[x];
}

dwhitney67
May 21st, 2010, 11:39 AM
Why didn't you use an STL string???



#include <string>
#include <iostream>

class Foo
{
public:
Foo() : str("ABC") {}

friend std::ostream& operator<<(std::ostream& os, const Foo& f)
{
os << f.str;
return os;
}
private:
std::string str;
};


int main()
{
Foo f;

std::cout << f << std::endl;
}

You can access each character of an STL string using the [] operator. For example, to access the second element of the string shown above:


char ch = str[1];

nvteighen
May 21st, 2010, 01:43 PM
Why didn't you use an STL string???


Because some people write C++ tutorials thinking C++ is C... and then people just use char * instead of std::string... *sigh*

dwhitney67
May 21st, 2010, 02:17 PM
I figured out what I wanted to do using a for loop:


string letters = "ABC";
for (int x = 0; x < sizeof(alpha); x +=1)
{
alpha[x] = letters[x];
}

Or this way:


#include <string>
#include <algorithm>
#include <iostream>

int main()
{
std::string letters("ABC");
char* array = new char[letters.size() + 1];

std::copy(letters.begin(), letters.end(), array);

std::cout << array << std::endl;
}