关于类对象和对象属性的地址探讨

#include <iostream>
#include <string>
using namespace std;
class person
{
public:
	person()
	{
		cout << "默认构造函数的调用" << endl;
	}
	person(int age)
	{
		m_age = age;
		cout << "有参构造函数的调用" << endl;
	}
	~person()
	{
		cout << "析构函数的调用" << endl;
	}
public:
	int m_age;
};
int main()
{
	person p(10);
	cout << "对象p的地址是:"<<(int*)&p << endl;
	cout << "p对象的属性p.m_age的地址是:" << (int*)&p.m_age << endl;

	person p1(p);
	cout << "对象p1的地址是:" << (int*)&p1 << endl;
	cout << "p1对象的属性p1.m_age的地址是:" << (int*)&p1.m_age << endl;
	cout << "p.m_age的值为10时,p1.m_age的值为:" << p1.m_age << endl;
	p.m_age = 20;
	cout << "若p.m_age改为20,则p1.m_age变成:"<<p1.m_age << endl; 
	system("pause");
	return 0; 
}

输出结果如图:
在这里插入图片描述
在实例化对象时,类对象的地址和对象成员变量的地址是一样的。经过拷贝构造函数,p对象拷贝一个新的临时对象p’赋值给p1,所以p和p1的地址不同,当p的成员变量改变时,p1的成员变量并没有改变。
但当对象的成员变量是指针时,经过系统调用默认拷贝构造函数,p1的成员变量指针和p的成员变量指针存储的地址是一样的,如下:

#include <iostream>
#include <string>
#include <ctime>
#include<cmath>
using namespace std;
class person
{
public:
	person()
	{
		cout << "默认构造函数的调用" << endl;
	}
	person(int age,int num,int score)
	{
		m_age = age;
		m_num=num;
		m_score = new int(score);
		cout << "有参构造函数的调用" << endl;
		//cout << "指针m_score的地址是:" << m_score << endl;
	}
	~person()
	{
		cout << "析构函数的调用" << endl;
	}
public:
	int m_age;
	int m_num;
	int* m_score;
};

int main()
{
	person p(10,10,100);
	cout << "p的成员变量指针m_score的地址是:" <<p.m_score << endl;
	cout << "p的成员变量m_age的地址是:" << &p.m_age << endl;
	cout << "p的成员变量m_num的地址是:" << &p.m_num << endl;
	cout << "p地址是:" << &p << endl;
	
	person p1(p);
	cout << "p1的成员变量指针m_score的地址是:" << p1.m_score << endl;
	cout << "p1的成员变量m_age的地址是:" << &p1.m_age << endl;
	cout << "p1的成员变量m_num的地址是:" << &p1.m_num << endl;
	cout << "p1的地址是:" << &p1 << endl;
	system("pause");
	return 0; 
}

在这里插入图片描述

程序结束后,两个对象的指针内存相继被释放,因为地址是一样的,所以同一地址会被释放两次,系统会报错,这就是浅拷贝带来的内存重复释放问题。值得注意的是,对象的第一个非指针成员变量和该对象的地址是一样的,如p和p的m_age的地址,以及p1和p1的m_age的地址都是一样的,第二个成员变量则还该对象的地址不同。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值