本篇文章主要介绍了"实现一个string类,包括构造、析构、拷贝构造及operator= 函数",主要涉及到方面的内容,对于C/C++jrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播感兴趣的同学可以参考一下:
C面试经常会出这样的题,以下是参考网上以及个人的一点理解:MyString.h#include
using namespac...
C++面试经常会出这样的题,以下是参考网上以及个人的一点理解:
MyString.h
#include
using namespace std;
class MyString
{
public:
//MyString(void);
MyString(const char* str = NULL); //定义些函数后,不能定义MyString(void);函数,否则构造无参数对象时,构造函数调用不明确,产生错误
MyString(const MyString& other);
~MyString(void);
MyString& operator = (const MyString& other);
bool operator==(const MyString &str);
friend ostream& operator<<(ostream& o,const MyString &str);
private:
char* m_data;
};
MyString.cpp
#include "MyString.h"
#include
//MyString::MyString(void)
//{
// m_data = new char[1];
// *m_data='\0';
// //m_data = NULL; //这样也行吧?
//}
MyString::MyString(const char *str)
{
if (str == NULL)
{
m_data = new char[1];
*m_data='\0';
}
else
{
int len=strlen(str);
m_data = new char[len+1];
strcpy(m_data,str);
}
}
MyString::MyString(const MyString &other)
{
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data,other.m_data);
}
MyString::~MyString(void)
{
delete []m_data;
m_data = NULL;
}
MyString& MyString::operator=(const MyString &other)
{
if (this == &other)
return *this;
delete []m_data;
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data,other.m_data);
return *this;
}
bool MyString::operator==(const MyString& str)
{
return strcmp(m_data,str.m_data) == 0;
}
//注意友元函数定义时不要friend,而且不要MyString::
ostream& operator<<(ostream& o,const MyString& str)
{
o<
#include "MyString.h"
void main(void)
{
MyString s1 = "hello";
MyString s2 = s1; //这是对象初始化,等效于MyString s2(s1),会调用类的拷贝构造函数
MyString s3;
s3 = s1; //这是赋值,注意与MyString s2 = s1;不同,会调用 =重载函数
MyString s4 = "hello";
cout<<"s1 = "<<>
运行结果:s = hello
s2 = hello
true
请按任意键继续. . .
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了实现一个string类,包括构造、析构、拷贝构造及operator= 函数,包括了方面的内容,希望对C/C++jrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播有兴趣的朋友有所帮助。
本文网址链接:http://www.codes51.com/article/detail_149779.html
相关图片
相关文章