类复制

类变量(非指针)直接的复制,只是把一个内存地址里的内容复制到另一个内存地址的内容,如下程序:

#include <iostream.h>
#include <String.h>
class Phone
{
public:
Phone(char *s);
~Phone();
void setPhone(char *s);
void display(char *s);
private:
char *sPhoneInfoPtr;
};
void main(void)
{
Phone MyPhone("(555)555-1234");
Phone HerPhone("(555)555-4321");


MyPhone.display("MyPhone");
HerPhone.display("HerPhone");


HerPhone = MyPhone;
MyPhone.display("MyPhone");
HerPhone.display("HerPhone");


MyPhone.setPhone("(999)999-9999");
MyPhone.display("MyPhone");
HerPhone.display("HerPhone");


}
Phone::Phone(char *s)
{
int iArrayLength;
iArrayLength = strlen(s) + 1;


sPhoneInfoPtr = new char[iArrayLength];
strcpy(sPhoneInfoPtr, s);
}
void Phone::setPhone(char *s)
{
sPhoneInfoPtr = s;
}
void Phone::display(char *s)
{
cout << s << "is" << sPhoneInfoPtr << endl;
}
Phone::~Phone()
{
delete sPhoneInfoPtr;
}

这里的输出会是:

Myphone is (555)555-1234

HerPhone is (555)555-4321

Myphone is (555)555-1234

HerPhone is (555)555-1234

Myphone is (999)999-9999

HerPhone is (555)555-1234

第二对输出前,HerPhone = MyPhone;只是把MyPhone的内容复制到HerPhone的内容里,因此第三对输出前,改变MyPhone的sPhoneInfoPtr并不改变HerPhone的sPhoneInfoPtr,所以输出不一样。

若MyPhone和HerPhone是Phone类型指针,则第三对输出结果会相同:

#include <iostream.h>
#include <String.h>
class Phone
{
public:
Phone(char *s);
~Phone();
void setPhone(char *s);
void display(char *s);
private:
char *sPhoneInfoPtr;
};
void main(void)
{
Phone *MyPhone = new Phone("(555)555-1234");
Phone *HerPhone= new Phone("(555)555-4321");


MyPhone->display("MyPhone");
HerPhone->display("HerPhone");


HerPhone = MyPhone;
MyPhone->display("MyPhone");
HerPhone->display("HerPhone");


MyPhone->setPhone("(999)999-9999");
MyPhone->display("MyPhone");
HerPhone->display("HerPhone");


}
Phone::Phone(char *s)
{
int iArrayLength;
iArrayLength = strlen(s) + 1;


sPhoneInfoPtr = new char[iArrayLength];
strcpy(sPhoneInfoPtr, s);
}
void Phone::setPhone(char *s)
{
sPhoneInfoPtr = s;
}
void Phone::display(char *s)
{
cout << s << "is" << sPhoneInfoPtr << endl;
}
Phone::~Phone()
{
delete sPhoneInfoPtr;
}

输出为:

Myphone is (555)555-1234

HerPhone is (555)555-4321

Myphone is (555)555-1234

HerPhone is (555)555-1234

Myphone is (999)999-9999

HerPhone is (999)999-9999


第二对输出前的HerPhone = MyPhone;这句赋值把两个指针变量指向同一个内存地址,因此对MyPhone的sPhoneInfoPtr修改也会造成对HerPhone的sPhoneInfoPtr的修改,所以第三对输出都一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值