通过成员函数 计算3个字符串的长度 不用strlen函数
时间: 2024-05-08 15:18:44 浏览: 6
好的,这个问题可以回答。我们可以定义一个成员函数,遍历字符串并计数,最后返回字符串长度。以下是一个例子:
```cpp
#include <iostream>
using namespace std;
class String {
private:
char* content;
int length;
public:
String(char* str = "") {
length = 0;
while (str[length] != '\0') {
length++;
}
content = new char[length + 1];
for (int i = 0; i < length; i++) {
content[i] = str[i];
}
content[length] = '\0';
}
int getLength() {
int len = 0;
while (content[len] != '\0') {
len++;
}
return len;
}
};
int main() {
String str1("Hello");
String str2("World");
String str3("!");
cout << str1.getLength() << endl;
cout << str2.getLength() << endl;
cout << str3.getLength() << endl;
return 0;
}
```
输出结果为:
```
5
5
1
```
请注意,我们在字符串的末尾添加了一个`\0`,因为该字符是C++中字符串的结束标志。如果没有它,我们可能会不小心读取字符串之外的内存,导致程序崩溃。