重写strncpy函数

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cassert>
#include<malloc.h>
char* str_ncpy(char* des,const char* sr,std::size_t n)
{
    std::size_t t;
    for(t=0;t<n;t++)
    {
        *(des+t)=*(sr+t);
    }
    *(des+n)= '\0';//别忘了字符串结尾符号
    return des;//返回目标字符串首地址
}
int main(void )
{
    char* str_test = "hello world!";
    char* str_des =(char*) malloc( strlen(str_test)+1);//分配内存,足够大
     std::cout<<str_ncpy( str_des,str_test,strlen(str_test) )<<std::endl;
    free(str_des);
    system("pause");
    return 0;
}






                
#include <iostream> #include <cstring> using namespace std; // 基类 Person class Person { protected: char Name[10]; char Sex; int Age; public: // 注册函数 void Register(char* name, int age, char sex) { strncpy(Name, name, sizeof(Name)); Name[sizeof(Name) - 1] = '\0'; // 确保字符串以'\0'结尾 Sex = sex; Age = age; } // 显示基本信息 void ShowMe() { cout << "姓名 " << Name << endl << "性别 " << (Sex == 'm' ? "男" : "女") << endl << "年龄 " << Age << endl; } }; // 派生类 Teacher class Teacher : public Person { private: char Dept[20]; int Salary; public: // 构造函数,调用基类的 Register 函数 Teacher(char* name, int age, char sex, char* dept, int salary) : Person() { Register(name, age, sex); strncpy(Dept, dept, sizeof(Dept)); Dept[sizeof(Dept) - 1] = '\0'; Salary = salary; } // 重写 ShowMe 函数 void ShowMe() { Person::ShowMe(); // 调用基类的 ShowMe cout << "工作单位 " << Dept << endl << "月薪 " << Salary << endl; } }; // 派生类 Student class Student : public Person { private: char ID[12]; char Class[12]; public: // 构造函数 Student(char* name, int age, char sex, char* id, char* classid) : Person() { Register(name, age, sex); strncpy(ID, id, sizeof(ID)); ID[sizeof(ID) - 1] = '\0'; strncpy(Class, classid, sizeof(Class)); Class[sizeof(Class) - 1] = '\0'; } // 重写 ShowMe 函数 void ShowMe() { Person::ShowMe(); // 调用基类的 ShowMe cout << "学号 " << ID << endl << "班级 " << Class << endl; } }; int main() { // 创建 Teacher 对象 Teacher teacher("章立早", 38, 'm', "电信学院", 2300); cout << "教师对象详细信息:" << endl; teacher.ShowMe(); cout << endl; // 创建 Student 对象 Student student("李木子", 22, 'f', "02035003", "能动01"); cout << "学生对象详细信息:" << endl; student.ShowMe(); return 0; }
最新发布
05-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值