c++函数strlen构造
时间: 2024-03-24 17:34:13 浏览: 14
C++函数`strlen`是一个用于计算字符串长度的函数,它定义在`<cstring>`头文件中。`strlen`函数的原型如下:
```cpp
size_t strlen(const char* str);
```
该函数接受一个指向以null结尾的字符数组(C风格字符串)的指针作为参数,并返回该字符串的长度,不包括null终止符。
`strlen`函数的实现原理是从给定的字符串起始位置开始逐个检查字符,直到遇到null终止符为止,然后返回字符的数量。
以下是一个使用`strlen`函数的示例:
```cpp
#include <iostream>
#include <cstring>
int main() {
const char* str = "Hello, World!";
size_t length = strlen(str);
std::cout << "Length of the string: " << length << std::endl;
return 0;
}
```
输出结果为:
```
Length of the string: 13
```
相关问题
C++深拷贝构造函数
深拷贝是指在进行对象拷贝时,不仅要拷贝对象本身,还要拷贝对象所指向的动态内存。C++中,深拷贝通常需要通过自定义拷贝构造函数来实现。
下面是一个示例代码,演了如何实现C++的深拷贝构造函数:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class String {
public:
String(const char* str = "") {
if (str == nullptr) {
m_data = new char[1];
*m_data = '\0';
} else {
m_data = new char[strlen(str) + 1];
strcpy(m_data, str);
}
}
// 拷贝构造函数
String(const String& other) {
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
// 析构函数
~String() {
delete[] m_data;
}
// 赋值运算符重载
String& operator=(const String& other) {
if (this != &other) {
delete[] m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
return *this;
}
void print() {
cout << m_data << endl;
}
private:
char* m_data;
};
int main() {
String str1("Hello");
String str2(str1); // 调用拷贝构造函数
String str3 = str1; // 调用拷贝构造函数
String str4;
str4 = str1; // 调用赋值运算符重载
str1.print(); // 输出:Hello
str2.print(); // 输出:Hello
str3.print(); // 输出:Hello
str4.print(); // 输出:Hello
return 0;
}
```
在上面的示例代码中,我们定义了一个String类,其中包含了一个char*类型的成员变量m_data,用于存储字符串。在构造函数中,我们通过new运算符为m_data分配了动态内存,并将字符串拷贝到了该内存中。在拷贝构造函数和赋值运算符重载中,我们同样需要为m_data分配动态内存,并将其他对象的m_data拷贝到该内存中,从而实现了深拷贝。
c++拷贝构造函数事例
以下是一个C++拷贝构造函数的例子:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class StringBad {
private:
char *str;
int len;
static int num;
public:
StringBad(const char *s) {
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
num++;
cout << "调用了构造函数" << endl;
}
StringBad(const StringBad &st) {
str = new char[strlen(st.str) + 1];
strcpy(str, st.str);
len = st.len;
num++;
cout << "调用了拷贝构造函数" << endl;
}
~StringBad() {
cout << "调用了析构函数" << endl;
delete [] str;
num--;
}
StringBad & operator=(const StringBad &st) {
if (this == &st) {
return *this;
}
delete [] str;
str = new char[strlen(st.str) + 1];
strcpy(str, st.str);
len = st.len;
cout << "调用了赋值运算符" << endl; return *this;
}
friend ostream & operator<<(ostream &os, const StringBad &st) {
os << st.str;
return os;
}
};
int StringBad::num = 0;
int main() {
StringBad s1("hello");
StringBad s2(s1);
StringBad s3 = s1;
StringBad s4("world");
s2 = s4;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << "当前对象数量:" << StringBad::num << endl;
return 0;
}
```