对象指针与动态对象

对象指针与动态对象

1. Accessing Object Members via Pointers (用指针访问对象成员)

Object pointers can be assigned new object names(对象指针可以指向新的对象名)

Arrow operator -> : Using pointer to access object members (箭头运算符 -> :用指针访问对象成员)

Circle circle1;
Circle* pCircle = &circle1; 
cout << "The radius is " << (*pCircle).radius    << endl;
cout << "The area is "   << (*pCircle).getArea() << endl;
(*pCircle).radius = 5.5;
cout << "The radius is " << pCircle->radius    << endl;
cout << "The area is "   << pCircle->getArea() << endl;

用指针访问对象成员

2. Creating Dynamic Objects on Heap (在堆中创建对象)

Object declared in a function is created in the stack.(在函数中声明的对象都在栈上创建); When the function returns, the object is destroyed (函数返回,则对象被销毁).

To retain the object, you may create it dynamically on the heap using the new operator. (为保留对象,你可以用new运算符在堆上创建它)

Circle *pCircle1 = new Circle{}; //用无参构造函数创建对象
Circle *pCircle2 = new Circle{5.9}; //用有参构造函数创建对象
//程序结束时,动态对象会被销毁,或者
delete pObject;  //用delete显式销毁
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值