对象指针
//声明形式
类名 对象指针名
Clock c(8, 3, 10);
Clock *ptr;
ptr = &c; //很像C语言的指针
//通过指针访问对象成员,一般是访问成员函数
ptr -> getHour();
//相当于(*ptr).getHour();
//也就是说在这里这两条语句时等效的
cout << ptr -> getHour() << endl;
cout << c.getHour() << endl;
this指针
//银汉鱼每一个类的成员函数中的特殊指针
//明确地指出了成员函数当前所操作的数据所属的对象
return hour;
//相当于
return this -> hour;
cout << hour << ":" << minute << ":" << second;
//相当于
cout << this -> hour << ":" << this -> minute << ":" << this -> second;
//有时候自己没有定义,系统会自动做this指针
//原来的写法
Clock :: Clock(int newH, int newM, int newS) {
hour = newH;
minute = newM;
second = newS;
}
//改进后的写法,有了this1后允许实参形参名称一样
Clock :: Clock(int hour , int minute , int second) {
this -> hour = hour;
this -> minute = minute;
this -> second = second;
}
1、动态创建对象
new 类型名T(初始化参数列表)
//功能:在程序执行期间,类似于malloc,并按初始化参数列表赋以初值
//结果:成功:T类型的指针,只相信分配的内存;失败:抛出异常
delete 指针p
//释放内存。p必须是new操作的返回值
//动态创建对象举例
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point() : x(0), y(0) {
cout << "Default Constructor called." << endl;
}
Point (int x, int y) : x(x), y(y) {
cout << "Constructor called." << endl;
}
~Point() {cout << "Destructor called." << endl; }
int getX() {return x;}
int getY() {return y;}
void move(int newX, int newY) {
x = newX;
y = newY;
}
};
int main() {
cout << "Step one:" << endl;
Point *ptr1 = new Point; //调用构造函数,由于没有括号,会调用无参构造函数
delete ptr; //自动调用析构函数
cout << "Step two:" << endl;
pre1 = new Point(1, 2);
delete ptr1;
return 0;
}
2、创建对象数组
//分配:new 类型名T[数组长度]
//数组长度可以是任意表达式,在运行时计算
//释放:delete[] 数组名p
//p必须是用new分配得到的数组首地址
//动态创建对象数组举例
#include <iostream>
using namespace std;
class Point {//类的声明同上 };
int main() {
Point *ptr = new Point[2]; //创建对象数组,每个元素都是一个Point对象
ptr[0].move(5, 10); //通过指针访问数组元素的成员函数
ptr[1].move(15, 20);
cout << "Deleting..." << endl;
delete[] ptr; //删除整个对象数组,记得加上方括号,表示我要删除的是个数组。这个过程中,对象释放,调用析构函数
return 0;
}
//new与delete要成对出现
Point ptr[2]和Point *ptr = new Point[2]有什么不同呢?
//区别在于,使用静态数组,长度固定,系统自动分配和释放内存。