刚学C++,自己写了个简单的mystring,有警告存在啊,const怎样用呢
- C/C++ code
#include <iostream>#include <cstring>//#include "Integer.h"using namespace std;class mystring {private: char* _s;public: mystring(int a){ _s = new char[a+1]; for(int i = 0; i < a; i++) _s[i] = ' '; _s[a+1] = '\0'; } /*21*/mystring( char* s ) { _s = new char[strlen(s)+1]; _s = s; } mystring( ) { _s = new char[1]; _s[0] = '\0'; } ~mystring() { delete []_s; } void display() { cout<<"<"<<_s<<">"<<endl; }};int main(){ mystring s1("sdfgfdgdf"); mystring s2(5); mystring s3; s1.display(); s2.display(); s3.display(); s3 = s1; s3.display(); return 0;}21行那一行有问题:
\one.cpp|21|warning: deprecated conversion from string constant to 'char*'|
求指教···
[解决办法]
_s = new char[strlen(s)+1];//申请一个长度为……的内存空间,将指针_s指向这个内存空间
_s = s;//将指针_s指向输入的指针s
你刚申请的空间转眼就被掷出窗外了
[解决办法]
_s = new char[strlen(s)+1]; strcpy(_s,s);