/*
* Copyright (c) 2015, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:刘畅
* 完成日期:2015年 4 月 11 日
* 版 本 号:v1.0
*
* 问题描述: 。
* 输入描述:NULL;
* 程序输出:按要求输出。
(1)阅读下面的程序,补足未完成的注释。
代码如下:
#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
char *a;
public:
A(char *aa)
{
a = new char[strlen(aa)+1]; //(a)这样处理的意义在于:<strong><u>避免a是野指针</u></strong>
strcpy(a, aa); //(b)数据成员a与形式参数aa的关系:<strong><u>将该对象的数据成员a复制为形式参数aa代表的字符串。</u></strong>
~A()
{
delete []a; //(c)这样处理的意义在于:<strong><u>释放申请的内存空间.</u></strong>
}
void output()
{
cout<<a<<endl;
}
};
int main(){
A a("good morning, code monkeys!");
a.output();
A b("good afternoon, codes!");
b.output();
return 0;
}
运行结果:
(2)将注释(a)所在的那一行去掉,会出现什么现象?为什么?为什么a数据成员所占用的存储空间要在aa长度基础上加1?若指针a不是指向字符(即不作为字符串的地址),是否有必要加1?
a变成野指针,程序运行后立即弹出错误的提示。
aa 后面还有个‘\0'。需要加1才能将aa这个字符串完全的复制、
没必要
(3)为类A增加复制构造函数,用下面的main函数测试
int main()
{
A a("good morning, code monkeys!");
a.output();
A b(a);
b.output();
return 0;
}
代码如下:
#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
char *a;
public:
A(char *aa)
{
a = new char[strlen(aa)+1];
strcpy(a,aa);
}
A(A &B)
{
a = new char[strlen(B.a)+1];
strcpy(a,B.a);
}
~A()
{
delete []a;
}
void output()
{
cout<<a<<endl;
}
};
int main()
{
A a("good morning, code monkeys!");
a.output();
A b(a);
b.output();
return 0;
}
运行结果:
知识点总结:
深复制的应用,不能让类中的作为数据成员的指针成为野指针。