c++ string和char用法

来源:互联网 发布:block matching算法 编辑:程序博客网 时间:2024/04/30 12:13
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;
}


0 0