c++ string和char用法

    xiaoxiao2021-03-25  112

    1.当char作为类的私有成员时: #include<iostream> #include<cstring> using namespace std; class A { private: char *c; //或用char []c; public: A(char *x) { c=new char[strlen(x)+1]; //当元素为char指针时,防止浅拷贝 strcpy(c,x); } void show() { cout<<c<<endl; } }; int main() { char n[10]="abc"; A a(n); a.show(); return 0; }

    2.当string作为私有类成员时:

    #include<iostream> #include<cstring>     using namespace std; class A { private:     string c; public:     A(string x)     {         c=x;     }     void show()     {         cout<<c<<endl;     } }; int main() {     char n[10]="abc";     A a(n);     a.show();     return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-15891.html

    最新回复(0)