输入代码1:
/*
* Copyright (c) 2015, 烟台大学计算机学院
* All rights reserved.
* 文件名称:sum123.cpp
* 作 者:林海云
* 完成日期:2015年4月11日
* 版 本 号:v2.0
*
* 问题描述:指针的复制
* 输入描述:NULL;
* 程序输出:按要求输出。
*/
#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
char *a;
public:
A(char *aa)
{
a = new char[strlen(aa)+1]; //(a)这样处理的意义在于:建立指针初始化,避免野指针的出现
strcpy(a, aa); //(b)数据成员a与形式参数aa的关系:将数据成员a复制为aa
~A()
{
delete []a; //(c)这样处理的意义在于:s释放申请的aa空间
}
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:
/*
* Copyright (c) 2015, 烟台大学计算机学院
* All rights reserved.
* 文件名称:sum123.cpp
* 作 者:林海云
* 完成日期:2015年4月11日
* 版 本 号:v2.0
*
* 问题描述:将注释(a)所在的那一行去掉,会出现什么现象?为什么?
为什么a数据成员所占用的存储空间要在aa长度基础上加1?若指针a不是指向字符(即不作为字符串的地址),是否有必要加1?
* 输入描述:NULL;
* 程序输出:按要求输出。
*/
#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]; //strlen<span style="font-family: Arial, sans-serif; line-height: 28px; text-indent: 10px; white-space: nowrap;">计算字符串的实际长度的函数</span>
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;
}
原文地址:http://blog.csdn.net/linhaiyun_ytdx/article/details/45000327