类和对象3【C++】
一、对象数组
数组的元素不仅可以是基本数据类型,也可以使自定义类型。对象数组中的每一个元素都是
类的对象。
声明一维对象数组的语法形式:
类名 数组名[常量表达式];
引用对象数组元素的公有成员:
数组名[下标] . 成员名;
数组中每一个元素对象被创建时,系统都会调用类构造函数初始化该对象。
- 通过初始化列表赋值。
Point A[2]={Point(1,2),Point(3,4)};
- 如果没有为数组元素指定显式初始值,数组元素便使用默认值初始化(调用默认构造函数)。
- 当数组中每一个对象被删除时,系统都要调用一次析构函数。
Example:
#include <iostream>
#include <cstring>
using namespace std;
class Student {
public:
Student(char* na, int i, int a);
int GetAge();
private:
char name[20];
int id;
int age;
};
Student::Student(char* na, int i, int a) {
strcpy(name, na);
id = i;
age = a;
}
int Student::GetAge() {
return age;
}
int main() {
int sum = 0;
Student s[5] = { Student("张三",10001, 20),//对象数组初始化
Student("李四",10002, 22),
Student("王五",10003, 24),
Student("赵六",10004, 26),
Student("孙七",10005, 28)
};
//累加每个学生的年龄
for (int i = 0; i < 5; i++) {
sum += s[i].GetAge();
}
cout << sum / 5 << endl;
return 0;
}
二、this指针
1. 为什么需要 this 指针?
每个对象中的数据成员都分别占有存储空间,而成员函数都是同一代码段。如果对同一个类
定义了 n 个对象。那么,当不同对象的成员函数引用数据成员时,怎么能保证引用的数据成员是属
于哪个对象呢?所以这时我们需要使用 this 指针来区别这些对象。
2. this 指针
C++ 除了接受原有的参数外,还隐含的接受了一个特殊的指针参数,这个指针称为 this 指
针。它是指向本类对象的指针,它的值是当前被调用的成员函数所在的对象的起始地址,既 this 指
针指向当前对象。
Example:
/*问题:
该代码中所有对象的成员函数对应的是同一个函数代码段。
那么程序如何确定分别输出的是a.x,b.x,c.x的值呢?
*/
#include<iostream>
using namespace std;
class A {
public:
A(int x1) {
x = x1;
}
void display() {
/*
当一个对象要调用成员函数时,
this指针中就装着该对象的地址,
成员函数就根据这个指针,
找到相应的数据,
然而进行相应的操作.
*/
cout << "this = " << this << " x = " << this->x << endl;
}
private:
int x;
};
int main() {
A a(1), b(2), c(3);
a.display();
b.display();
c.display();
return 0;
}
this 指针最常用于:
(1)区分与局部变量重名的数据成员;
(2)返回当前对象
(3)在成员函数中获取当前对象地址。
Example:
#include <iostream>
using namespace std;
class X {
public:
X(int M) {
m = M;
}
void setValue(int m) {
this->m = m; //区分与函数参数重名的数据成员
cout << "this:" << this << " m = " << m << endl;
}
X& add(const X &a) {
m += a.m;
cout << "this:" << this << " m = " << m << endl;
return *this; //返回当前对象
}
void copy(const X& a){ //拷贝对象
if (this == &a) { //如果是同一对象,则不需拷贝
cout << "this:" << this << " m = " << m << endl;
return;
}
m = a.m; //拷贝操作
cout << "this:" << this << " m = " << m << endl;
}
private:
int m;
};
int main() {
X x(5);
X a(x);
x.setValue(5);
x.add(5);
x.copy(5);
cout << endl;
a.setValue(5);
a.add(5);
a.copy(5);
return 0;
}