1·题目介绍
2·参考程序
#include<iostream>
#include<cstring>
using namespace std;
class String_Integer
{
private:
char* s;
public:
String_Integer(char* str)
{
s = new char[strlen(str) + 1];
strcpy(s, str);
}
operator int()
{
int num = 0;
char* p = s;
for (p = s; *p ; p++)
{
if (*p >= '0' && *p <= '9')
{
num = num * 10 + *p - '0';
}
}
return num;
}
void show()
{
cout << s << endl;
}
~String_Integer()
{
delete[]s;
}
};
int main()
{
char a[20] = { "ab12 3c00d45ef:" };
String_Integer test(a);
test.show();
int n = test;
cout << n;
return 0;
}
3·心得收获
a·当遇到要为字符串指针申请空间时,已形参的长度+1为空间长度来申请
b·当我们需要使用指针条件来进行循环时,初始值应等于它的变量名(首地址),而不应该等于0,截止条件也可以写成*p,即此时字符串数组循环到头了。