对象指针与动态对象
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显式销毁