C++基本问题求教:自定义的string1 (kingofark)
用Borland C++ Compiler 5.5 编译通过,运行正常;
用Visual C++ 6.0 编译通过,运行的时候出现“写”错误。
程序注释中有部分疑惑。
#include <iostream>
#include <string>
using namespace std;
class string1
{
public:
string1(char* value):data(value) { }
~string1() { delete[] data; }
string1(const string1& str) { data = str.data; }
string1& operator=(string1& str)
{
if (this == &str)
return *this;
delete[] data;
data = new char[20];
strcpy(data, str.data);
return *this;
}
operator char * () const { return data; } //干嘛用的?怎么使用?
private:
char* data;
};
int main()
{
char* p1;
p1 = new char[20];
strcpy(p1, "abcdef");
cout << "p1 = " << p1 << " " << &p1 << endl;
string1 str("abcd");
cout << "str = " << str << endl; // ???
p1 = str;
cout << "p1 = str, p1 = " << p1 << endl;
strcpy(p1,"sdf"); // 在 MSVC 6 中,这里出现“写”错误
cout << "strcpy(p1, \"sdf\"), p1 = " << p1 << endl;
delete[] p1;
p1 = NULL;
return 0;
}
请大家不吝赐教,谢谢!