您的位置:首页 > 其它

strcpy_s不接受两个参数 String的实现

2014-05-05 23:40 585 查看
#include <iostream>

#include <cstring>

using namespace std;

class String

{

public:
//String();   //default constructor
String(const char * str =NULL);   //common constructor
String(const String& another);   //copy constructor

~String();   //destructor

String& operator=(const String& another);
friend ostream & operator <<(ostream& output, String& str );
friend istream & operator >>(istream& input , String& str);

private:
char * m_data;

};

//default constructor

//when to use it:

//String a;  

//owner don't write it, while write constrcutor with parameter, 

//Q: m_data is NULL; 

//or m_data=new char[0]; m_data='\0';

//A:

/*

String::String()

{
cout << "Call 'Default Constructor'" << endl;
m_data = NULL;

}

*/

//common constructor

//String a("Hello World!");

//Q: whether judge str is null

//if str == NULL; then m_data is null or '\0'

//A:

String::String(const char* str)

{
cout << "Call 'Common Constructor'" << endl;
m_data = new char[strlen(str)+1];
strcpy_s(m_data,str);

}

//copy constructor 

// String a(b);  //b is an object of String

String::String(const String& another)

{
cout << "Call 'Copy Constructor'" << endl;
m_data = new char[strlen(another.m_data)+1];
strcpy_s(m_data,another.m_data);

}

//destructor

//in the final scope of the object

String::~String()

{
cout << "Call 'Destructor'" << endl;
delete[]m_data; 
// or just delete m_data;  //as char* is a data type

}

String& String::operator=(const String& another)

{
cout << "Call 'Overload ='" << endl;
//1 judge this == another
//by address
if (this == &another )
{
return *this;
}

//2 free prevoius memory
delete []m_data;

//3 allocating new memory
this->m_data = new char[strlen(another.m_data)+1];
strcpy_s(this->m_data,another.m_data);

//4 return this
return *this;

}

ostream& operator<<(ostream &output, String &str)

{
cout << "Call 'Overload <<'" << endl;
output << str.m_data;
return output;

}

istream& operator>>(istream &input, String &str)

{
cout << "Call 'Overload >>'" << endl;
input >> str.m_data;
return input;

}

int main()

{
String a("Hello ");
String b("World!");
cout << a << b << endl;

cin >> a >> b;
cout << a << b << endl;

system("pause");
return 0;
}

在VS2013上还没build成功,因为strcpy_s不接受两个参数, 亲们帮忙看看是什么原因?

解决方法之:add the second parameter in strcpy_s

int length=strlen(anoter.m_data);

用strcpy_s(m_data,length+1,another.m_data)替换strcpy_s(m_data,another.m_data);  build succeed

但是 触发新的断点  太晚了 稍后更新
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string strcpy vs class
相关文章推荐