自考新教材-p161

Posted duanqibo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自考新教材-p161相关的知识,希望对你有一定的参考价值。

源程序:

#include<iostream>
using namespace std;

class pointer
{
public:
int a;
int *p; //指向整型数的指针
pointer()
{
a=100;
p=new int(10);
}
pointer(const pointer &tempp) //复制构造函数
{
if(this != &tempp)
{
a=tempp.a;
p=new int();
*p=*tempp.p;
}
}
~pointer()
{
if(p!=NULL)
delete p;
}
pointer &operator=(const pointer &c)//成员函数
{
if(this == &c)
return *this; //避免a=a这样的赋值
delete this->p; //释放原来的空间
this->p = new int(*c.p); //申请新空间保存值
return *this;
}
};

int main()
{
pointer p1; //使用默认构造函数
pointer p2(p1); //使用复制构造函数
pointer p3;
p1=p1; //用来测试
p3=p1; //使用复制构造函数
cout<<" 初始化后,各对象的值及内存地址"<<endl;
cout<<"对象名 对象地址 a的值 p中的值 p指向的值 p的地址"<<endl;
cout<<"p1: "<<&p1<<","<<p1.a<<","<<p1.p<<","<<*p1.p<<","<<&p1.p<<endl;
cout<<"p2: "<<&p2<<","<<p2.a<<","<<p2.p<<","<<*p2.p<<","<<&p2.p<<endl;
cout<<"p3: "<<&p3<<","<<p3.a<<","<<p3.p<<","<<*p3.p<<","<<&p3.p<<endl;
*p1.p=20;
p2.a=300;
cout<<" 修改后,各对象的值及内存地址"<<endl;
cout<<"对象名 对象地址 a的值 p中的值 p指向的值 p的地址"<<endl;
cout<<"p1: "<<&p1<<","<<p1.a<<","<<p1.p<<","<<*p1.p<<","<<&p1.p<<endl;
cout<<"p2: "<<&p2<<","<<p2.a<<","<<p2.p<<","<<*p2.p<<","<<&p2.p<<endl;
cout<<"p3: "<<&p3<<","<<p3.a<<","<<p3.p<<","<<*p3.p<<","<<&p3.p<<endl;
return 0;
}

运行结果:

技术图片

 

以上是关于自考新教材-p161的主要内容,如果未能解决你的问题,请参考以下文章

自考新教材-p181

自考新教材-p156

自考新教材-p159

自考新教材-p286

自考新教材-p285

自考新教材--p179