Saturday, May 9, 2009

Constructors and C array question in C++?

How can I take a type I've created and initalize it with a C string or character array?





ex:








MyType x("initalize to this char array");








How can I make this legal?





MyType::MyType(char ar[])


:


{


for(int i = 0; i %26lt; (sizeof(ar)/sizeof(ar[0])); ++i){


private_member_array[i] = ar[i];


};





}











So basically,





What would be the parameter in my constructor, to make it legal to pass it char array's in the form of:





MyType("data for my type");





Thanks!

Constructors and C array question in C++?
A working anwer:-





#include %26lt;iostream%26gt;


#include "MyType.h"


int main (int argc, char * const argv[])


{


MyType* mt = new MyType("data for my type");


std::cout %26lt;%26lt; char(mt-%26gt;pm_array[0]);


return 0;


}





// header MyType.h


class MyType


{


public:


int pm_array[];


MyType(char ar[]);


};





#include "MyType.h"


MyType::MyType(char ar[])


{


for(int i = 0; i %26lt; (sizeof(ar)/sizeof(ar[0])); ++i)


{


pm_array[i] = ar[i];


}


}
Reply:There are different ways to do it.


First could be use char*. (include string.h)





class MyType {


private:


char *private_str;


public:


MyType();


MyType(char*);


~MyType();


}





MyType::MyType() {


private_str = NULL;


};


MyType::MyType(char* str) {


private_str = new char[strlen(str)];


strcpy(private_str,str);


};


//Helps to free memory on destruction.


MyType::~MyType() {


if (private_str) delete private_str;


};





Another way could be to use string. (include string)





class MyType {


private:


std::string private_str;


public:


MyType(std::string%26amp;);





}





MyType::MyType(std::string %26amp;str) {


private_str = str;


};





I hope this helps!!
Reply:Templates
Reply:The correct argument to the constructor is either a character array (as you did) or a character pointer. If you have a character array, use strcpy to copy from the literal to the array. If you have a pointer, you can use assignment.





See http://c-faq.com/decl/autoaggrinit.html . http://cppreference.com/





Take note that if you use a pointer, you can't modify the string contents. But you can with an array.
Reply:I think you're looking for





MyType::MyType (const char * text)





Note that I strongly recommend to use std::string for the internal storage of the string. Handles the classical zero terminated string issues of overruns, memory allocation, concatenation much more pleasantly that C strings.

daisy

No comments:

Post a Comment