C++面试经常会出这样的题,以下是参考网上以及个人的一点理解:
MyString.h
#include<iostream>
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;
};
#include<iostream>
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 <string>
//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<<str.m_data;
return 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 = "<<s1<<endl;
cout<<"s2 = "<<s2<<endl;
cout<<boolalpha<<(s4 == s1)<<endl;
getchar();
}
运行结果:
s1 = hello
s2 = hello
true
请按任意键继续. . .