题目来源:http://blog.csdn.net/hackbuteer1/article/details/6823272
3、const 有什么用途?(请至少说明两种)
答:(1)可以定义 const 常量。(2)const可以修饰函数的参数、返回值,甚至函数的定义体。被const修饰的东西都受到强制保护,可以预防意外的变动,能提高程序的健壮性。
5、下面是交换两个double型数据的函数,
- void swap( double* p1, double* p2 )
- {
- double *p;
- *p = *p1;
- *p1 = *p2;
- *p2 = *p;
- }
- void main()
- {
- double a = 0.1;
- double b = 0.2;
- swap( &a, &b );
- }
请找出上述代码的错误,指出错误的原因,并改正。
答:函数swap中混淆了double型指针与double型变量的差别,对于一个未初始化的指针访问其内存空间是非常危险的。对swap函数修改如下:
- void swap( double* p1, double* p2 )
- {
- double p;
- p = *p1;
- *p1 = *p2;
- *p2 =p;
- }
6、在电信业务的后台处理程序中,经常会涉及到处理字符串,除了用char *处理字符串之外,C++还为我们提供了封装了的字符串类string,其本质也是用一个动态数组来保存字符串,类String的原型为:
- class String
- {
- public:
- String(const char *str = NULL); // 普通构造函数
- String(const String &other); // 拷贝构造函数
- ~String(void); // 析构函数
- String & operator =(const String &other); // 赋值函数
- private:
- char *m_data; // 用于保存字符串
- };
请编写String的上述4个函数普通构造函数、拷贝构造函数、析构函数和赋值函数。
代码如下:
- class String
- {
- private:
- char *m_data; //私有成员,保存字符串
- public:
- String(const char *str = NULL); //普通构造函数
- String(const String &other); //复制构造函数
- ~String(void); //析构函数
- String & operator =(const String &other); //赋值函数
- };
- String::String(const char *str = NULL) //带一个指针的普通构造函数
- {
- if(str == NULL)
- {
- m_data = new char[1]; //分配一个字节
- assert(m_data != NULL);
- *m_data = '\0';
- }
- else
- {
- m_data = new char[strlen(str)+1]; //分配空间容纳str内容
- assert(m_data != NULL);
- strcpy(m_data,str);
- }
- }
- String::String(const String &other) //拷贝构造函数
- {
- m_data = new char[strlen(other.m_data)+1];
- assert(m_data != NULL);
- strcpy(m_data,other.m_data);
- }
- String::~String(void) //析构函数
- {
- if(m_data != NULL)
- {
- delete []m_data;
- m_data = NULL;
- }
- }
- String & String::operator=(const String &other) //赋值函数
- {
- if(&other == this) //如果对象与other是同一个对象
- return *this;
- delete []m_data; //释放堆内存
- m_data = new char[strlen(other.m_data)+1];
- assert(m_data != NULL);
- strcpy(m_data,other.m_data);
- return *this;
- }