C ++ implements the String class and the string class
This is a very classic interview question. You can check whether students have a comprehensive understanding of C ++ in a short time. The answer should include the majority of C ++ class knowledge, ensure that the String class can complete the assignment, copy, and definition of variables.
# Include <iostream> using namespace std; class String {public: String (const char * str = NULL); String (const String & other );~ String (void); String & operator = (const String & other); private: char * m_data;}; String: String (const char * str) {cout <"constructor called" <endl; if (str = NULL) // avoid the occurrence of a wild pointer, such as String B. if no such sentence exists, the wild // pointer {m_data = new char [1]; * m_data = ''/0'';} else {int length = strlen (str ); m_data = new char [length + 1]; strcpy (m_data, str) ;}} String ::~ String (void) {delete m_data; cout <"destructor called" <endl;} String: String (const String & other) {cout <"the value assignment constructor is called" <endl; int length = strlen (other. m_data); m_data = new char [length + 1]; strcpy (m_data, other. m_data);} String & String: operator = (const String & other) {cout <"the value assignment function is called" <endl; if (this = & other) // you do not need to copy the return * this; delete m_data; // delete the previous memory space pointed to by the pointer variable in the assigned object, avoid // Memory leakage int length = strlen (other. m_data); // calculate the length of m_data = new char [length + 1]; // apply for the space strcpy (m_data, other. m_data); // copy return * this;} void main () {String B; // call the constructor String a ("Hello "); // call the constructor String c ("World"); // call the constructor String d = a; // call the value assignment constructor, because a is used to initialize d = c during object d creation; // call the value assignment function after overload}
C \ C ++ for stringh header files and string classes
You can use a standard string or CString. Use string if there is no need.
The reason why CString exists is that it is historical. When CString was born, the C ++ standard was not available yet.
-- Question added: Why can't I use a string for Turbo C ++ 3.0?
-- Tc 3 can be used to compile c ++. Why can't I even use string?
The C ++ standard came out in 98 years. Tc3 came out 98 years ago, so you should use the compiler of the new point. With VC2005, this is more in line with the standard
Is there any String variable type in C?
No. You can define it yourself.
Typedef char * string