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

#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

但是 触发新的断点  太晚了 稍后更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值