C++面试题-String函数实现
2013-05-10 09:32
337 查看
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;
}
相关文章推荐
- C++面试题-String函数实现
- C++面试题-String函数实现
- C++面试题:介绍一下STL如何实现vector
- C++ 选择排序算法的实现与改进(含笔试面试题)
- C++【常见面试题】String类的实现,以及深拷贝、浅拷贝问题
- 华为面试题——约瑟夫问题的C++简单实现(循环链表)
- C++面试题 用俩个栈(队列)实现一个队列(栈)
- 华为经典面试题---大数乘法的c++实现
- 【C++】链表实现的各种情况(含面试题)
- C++ 堆排序算法的实现与改进(含笔试面试题)
- C++【面试题】:类实现万年历(日期计算器),(含构造函数、拷贝构造、运算符重载、析构函数)
- C++实现to_string函数--int to string
- c++面试题2:虚函数是如何实现的?
- C++面试题:介绍一下STL,STL如何实现vector
- C++面试题之模拟实现string类
- C++面试题,自己实现String类的构造函数,拷贝构造函数,赋值操作符,append,replace,+运算符重载等
- C++面试题:介绍一下STL,STL如何实现vector
- C++常考面试题:实现内存拷贝函数
- 华为面试题——约瑟夫问题的C++简单实现(循环链表)
- C++面试题:两个队列实现一个栈