#include<iostream> #include<cstring> using namespace std; class Student{ public : Student(char *name1, char *stu_no1, float score1); ~Student(); void disp(); private : char *name; char *stu_no; float score; }; Student::Student(char *name1, char *stu_no1, float score1){ name = new char [strlen(name1) + 1]; strcpy(name, name1); stu_no = new char [strlen(stu_no1) + 1]; strcpy(stu_no, stu_no1); score = score1; } Student::~Student(){ delete []name; delete []stu_no; } void Student::disp(){ cout << "name: " << name << endl; cout << "stu_no: " << stu_no << endl; cout << "score: " << score << endl; } int main(){ Student stu1("Li ming" , "20080201" , 90); stu1.disp(); Student stu2("Wang fang" , "20080202" , 85); stu2.disp(); return 0; }
报错:warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
解决:
1)根据warning,第一个方法,该strcpy为strcpy_s
strcpy_s定义:
errno_t __cdecl strcpy_s(_Out_writes_z_(_SizeInBytes) char * _Dst, _In_ rsize_t _SizeInBytes, _In_z_ const char * _Src);
注意strcpy_s中多了第二个参数,限制复制字符串的长度,避免越界。
微软的警告,主要因为那些C库的函数,很多函数内部是不进行参数检测的(包括越界类的),微软担心使用这些会造成内存异常,所以就改写了同样功能的函数,改写了的函数进行了参数的检测,使用这些新的函数会更安全和便捷。关于这些改写的函数你不用专门去记忆,因为编译器对于每个函数在给出警告时,都会告诉你相应的安全函数,查看警告信息就可以获知,在使用时也再查看一下MSDN详细了解。
本例中,修改代码为:
Student::Student( char *name1, char *stu_no1, float score1){ name = new char [strlen(name1) + 1]; <strong>strcpy_s(name, strlen(name1) + 1, name1);</strong> stu_no = new char [strlen(stu_no1) + 1]; <strong>strcpy_s(stu_no, strlen(stu_no1) + 1, stu_no1);</strong> score = score1; }
即可。
2)根据warning,第二个方法,To disable deprecation, us _CRT_SCURE_NO_WARNINGS. 找到项目--属性--配置属性--C/C++--命令行--其它选项 中填上【 /D "_CRT_SECURE_NO_DEPRECATE"】(注:中括号中的全部内容)。
或者 在源程序一开始 加上
#pragma warning(disable : 4996)