#include <iostream>
#include <cstring>
using namespace std;
class Date
{
public:
Date(int y=2000,int m=1,int d=1)
{
year=y;
month=m;
day=d;
}
void SetDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void PrintDate() const
{
cout<<year<<","<<month<<","<<day<<endl;
}
private:
int year,month,day;
};
class Student
{
public:
Student(int y,int m,int d,int num,char* pname="no name"):birthday(y,m,d)
{
code=num;
strncpy_s(name,pname,sizeof(name)); //?
name[sizeof(name)-1]='\0' ; //?
}
void SetStudent(int y,int m,int d,int num ,char* pname)
{
code=num;
strncpy_s(name,pname,sizeof(name)); //?
name[sizeof(name)-1]='\0' ; //?
cout<<name<<endl;
}
void PrintStudent() const
{
cout<<"序号:"<<code<<"\t姓名:"<<name<<"\t出生日期"<<endl;
birthday.PrintDate();
cout<<endl;
}
private:
int code;
char name[20];
Date birthday;
};
int main()
{
Student stu(1985,10,1,1001);
stu.PrintStudent();
}
"c++ strncpy_s" 是一个 C++ 中的字符串操作函数,用于将源字符串中的一定数量的字符复制到目标字符串中。它是一个安全版本的字符串拷贝函数,可以防止缓冲区溢出。
"name[sizeof(name)-1] = '\0'" 的作用是在字符串末尾添加一个空字符,以确保字符串以 NULL 结束。这是为了避免在使用该字符串时发生错误或出现问题。如果没有这个空字符,可能会导致程序读取或写入超出缓冲区的内存,从而发生未定义的行为或崩溃。
debug显示c++forbid convert a string constant to char*
C++的string和C语言的char ,两者不兼容,如果要转换,可以用 string.c_str 这个属性得到 char
strncpy_s 是什么意思啊?
这是安全版本的,字符串拷贝函数,将第二个字符串指针的内容拷贝到第一个
name[sizeof(name)-1]='\0' 不懂有什么用啊
这是截取字符串,而且写错了,应该把sizeof(name)写成 strlen(name)
strncpy_s 函数是将源字符串中指定的前n个字符复制到目的字符串
name[sizeof(name)-1] = '\0' 可以不需要,strncpy_s应该是自动带字符串结束符的