Tuesday, July 14, 2009

C++ prog. Problems with a String class. (the same as in my previous question): what's wrong with it? copy fct?

.h::::::::::::::::::::::::::::::::::::::...


#ifndef STRING_H


#define STRING_H


#include %26lt;iostream%26gt;


namespace HomeMadeString


{


class String


{


unsigned int elementsNum;


char*pData;


public:


String()


{


elementsNum=0;


char*pData=NULL;


}


String(String %26amp;theOther);


String(const char* c1);


String(char c, unsigned int times);


~String()


{


delete[] pData;


}


void getStr(char * pBuff);


unsigned int getLength(){return elementsNum;}


void print(std::ostream%26amp; os);


char getChar(unsigned int pos);


static String concatenate(String string1, String string2);


static bool compare(String string1, String string2);


static void copy(String%26amp; string1, String string2);//it copies the second string into the first


};


}


#endif


.cpp::::::::::::::::::::::::::::::::


How to write the "copy" function?


The "print" function?





Please help!





Domonkos

C++ prog. Problems with a String class. (the same as in my previous question): what's wrong with it? copy fct?
You get that char*pData inside your constructor is a separate declaration, it does not reference the class-scope variable with the same name (and it falls out of scope when the constructor returns.





Also, your code is conspicuously lacking any allocations -- don't rely on memory allocated by the caller, it could go away at any time.





More, avoid implementation inside of the .h file, it will bite you in the butt when your projects become complex.





Copying an object is usually done as a self-referential overload of the constructor, accepts parameter of its own class.





Not sure what you want print() to do, print to a printer? Doesn't seem to make much sense. If you mean print to console, what's wrong with printf() or stream output?





Good Luck


No comments:

Post a Comment