+ 3
How can use char pointer, in private class and use them, to a string or char in my program pls help if can
3 ответов
+ 3
This answer will be used to contrast what the other answer(s) given that state to use std::string (and those answers are correct -- usestd::string).
Let's assume that you could only use char *, you can't for some reason use std::string, and that you are dealing with NULL terminated strings. This is a synopsis of what your implementation would have to do (and please compare this with simply using std::string):
#include <algorithm> #include <cstring> class A { public: // construct empty string A () : str(new char[1]()) {} // construct from non-empty A(const char *s) : str(new char[strlen(s) + 1]) { strcpy(str, s); } // copy construct A(const A& rhs) : str(new char[strlen(rhs.str) + 1]) { strcpy(str, rhs.str); } // destruct ~A() { delete [] str; } // assign A& operator=(const A& rhs) { A temp(rhs); std::swap(str, temp.str); return *this; } // setter void setStr(char * s) { A temp(s); *this = temp; } // getter const char* getStr() { return str; } private: char * str; };
Live Example
After adding a couple more constructors and a getter function, this follows the Rule of 3.
You see how much code we needed to add just to make the class safely copyable and assignable? That's why usingstd::string is much more convenient than using char *when it comes to class members. For std::string a single line needs to be changed, compared to adding the copy / assignment (and move, which I didn't show) functions.
The bottom line is that in C++ if you want strings, use strings (std::string) and try to keep away from using char * (unless you have a very compelling reason to be using char * to represent string data).
0
@Atul thank you for time & input
0
Let get a basic understanding of object programming. In object programming data can be hidden with object or class you create. Private is method use hide data. Public data the whole program can see data.
Example: in a bank people are deal with checks you write or deposit. The bank does not want such employees to know your personal data such as social security number, phone number or address you live. It is private and cannot be accessed by mist employees. The process is called hiding data of clients from most employees. Most can only access public data to do their job!