类变量(非指针)直接的复制,只是把一个内存地址里的内容复制到另一个内存地址的内容,如下程序:
#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的修改,所以第三对输出都一样。