C++面试题-String函数实现
面试中经常会出现让应聘者写出string的构造函数、析构函数等具体实现,有人说会了这道题,那么C++的基础知识可以说是会了60%.
而且在前几天我同学参加的面试中也出现了这道题目,足以证明不负其名。为以后实习工作打算,现在将其总结一下。
在网上搜了搜,发现很多文章列出了实现代码,但在重载“赋值函数”时都将operator错写成了operate,大家在参考代码的时候一定要注意。
为方便测试,我还重载了输出符“<<”和输入符“>>”。
最后给出了测试代码。
#include <iostream>
using namespace std;
class String
{
public:
String(const char *str = NULL); // 通用构造函数
String(const String &another); // 拷贝构造函数
~ String(void); // 析构函数
friend String & operator = (const String &rhs); // 赋值函数
friend ostream& operator << (ostream& output, String & str); //重载输出符 “<<”
friend istream& operator >> (istream& input, String& str);//重载输入符 >>
private:
char *m_data; // 用于保存字符串
};
istream& operator >> (istream& input, String& str)
{
input >> str.m_data;
return input;
}
ostream& operator << (ostream &output, String &str)
{
output << str.m_data;
return output;
}
String::~ String()
{
cout << "Destructing !" << endl;
delete m_data;
}
String::String(const char *str)
{
if(str == NULL)
{
this->m_data = new char[1];
this->m_data = '\0';
}
else
{
this->m_data = new char[strlen(str) + 1];
strcpy(m_data, str);
}
}
String::String(const String& another)
{
this->m_data = new char[strlen(another.m_data) + 1];
strcpy(this->m_data, another.m_data);
}
String& String::operator = (const String &other)
{
if(this == &other)
return *this;
delete m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
int main()
{
String a("hello");
String b("world!");
cout << a << " " << b << endl;
cin >> a >> b;
cout << a << " " << b << endl;
return 0;
}