会飞的蝌蚪君

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C++中使用函数strcpy时出现问题:

 

解决方案:

在文件开头添加语句:

1 #pragma warning(disable:4996)

done!

 

 

剑指offer:

第一题:赋值运算符函数

 1 #include "stdafx.h"
 2 #include<iostream>
 3 #include<string>
 4 #pragma warning(disable:4996)   //debug
 5 
 6 
 7 using std::cout;
 8 using std::endl;
 9 
10 
11 
12 
13 class mystring
14 {
15 public:
16     mystring(char* data = nullptr);
17     mystring(const mystring & str);
18     ~mystring();
19     mystring & operator=(const mystring & s);
20     void print();
21 private:
22     char* m_data;
23 };
24 
25 
26 
27 mystring::mystring(char* data)
28 {
29     if (data == nullptr)
30     {
31         data = new char[1];
32         data[0] = '\0';
33 
34     }
35     else
36     {
37         int length = strlen(data);
38         m_data = new char[(length + 1)];
39         strcpy(m_data, data);
40 
41     }
42 }
43 
44 mystring::mystring(const  mystring & s)
45 {
46     int length = strlen(s.m_data);
47     m_data = new char[(length + 1)];
48     strcpy(m_data, s.m_data);
49 
50 }
51 
52 mystring::~mystring()
53 {
54     delete[]m_data;
55 }
56 
57 mystring & mystring::operator=(const mystring & s)
58 {
59     if (this == &s)
60         return *this;
61     
62     delete[]m_data;
63     m_data = nullptr;
64 
65     m_data = new char[strlen(s.m_data) + 1];
66     strcpy(m_data, s.m_data);
67 
68 }
69 
70 
71 void mystring::print()
72 {
73     cout<<("s%", m_data)<<endl;
74 
75 }
76 
77 
78 int main()
79 
80 {
81     mystring kk = "hello";
82     mystring nn;
83     nn = kk;
84     kk.print();
85     nn.print();
86     system("pause");
87     return 0;
88 }

 

posted on 2018-04-24 14:11  会飞的蝌蚪  阅读(3992)  评论(0编辑  收藏  举报