strcpy的自我实现
时间: 2024-04-10 07:25:11 浏览: 60
strcpy是一个C语言中常用的字符串复制函数,用于将一个字符串的内容复制到另一个字符串中。下面是一个简单的自我实现示例:
```c
#include <stdio.h>
char* strcpy_custom(char* dest, const char* src) {
if (dest == NULL || src == NULL) {
return NULL;
}
char* temp = dest;
while ((*temp++ = *src++) != '\0') {
;
}
return dest;
}
int main() {
char src[] = "Hello, CSDN!";
char dest[20];
strcpy_custom(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}
```
在自我实现的strcpy_custom函数中,我们首先判断了目标字符串dest和源字符串src是否为空指针,如果为空则返回NULL。然后我们使用一个指针temp指向目标字符串dest的起始位置,通过循环将源字符串src的每个字符逐个复制到目标字符串dest中,直到遇到字符串结束符'\0'为止。最后返回目标字符串dest。
相关问题
解释下面一段代码if (this == &s) { return *this; } delete[] str; str = new char[strlen(s.str) + 1]; strcpy(str, s.str); return *this;
这是一个重载赋值运算符的实现代码,用于将一个对象的值赋给另一个对象。其中:
- `this == &s` 判断当前对象是否与传入的参数对象相同,如果相同,则直接返回当前对象的引用,避免自我赋值的情况出现。
- `delete[] str` 释放当前对象中存储的字符串内存空间,避免内存泄漏。
- `str = new char[strlen(s.str) + 1]` 申请新的字符串内存空间,长度为传入对象的字符串长度加一(为了存储字符串结尾的 '\0')。
- `strcpy(str, s.str)` 将传入对象中的字符串复制到当前对象的字符串中。
- `return *this` 返回当前对象的引用,以便链式赋值操作。
2、请发挥自己的想象力,设计并实现一个Human类,并测试其相应功能 序号 属性名 属性意义 数据类型 访问控制权限 1 age 年龄 int private 2 name 姓名 char * private 功能 : 获取 char * getName(); int getAge(); void introduce();//输出一段自我介绍,包括姓名
和年龄
以下是Human类的实现代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Human {
private:
int age;
char *name;
public:
Human(int age, const char *name) {
this->age = age;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
~Human() {
delete[] name;
}
char *getName() {
return name;
}
int getAge() {
return age;
}
void introduce() {
cout << "Hello, my name is " << name << ", and I am " << age << " years old." << endl;
}
};
int main() {
Human h(20, "Tom");
cout << "Name: " << h.getName() << endl;
cout << "Age: " << h.getAge() << endl;
h.introduce();
return 0;
}
```
运行结果:
```
Name: Tom
Age: 20
Hello, my name is Tom, and I am 20 years old.
```
以上就是Human类的设计和实现,包括属性和方法的定义,以及相应的测试代码。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)