C++之对象数组

柔情痞子 提交于 2020-02-22 18:00:48

对象数组的定义与访问

定义对象数组
  类名 数组名[元素个数];

访问对象数组元素
  通过下标访问
  数组名[下标].成员名

对象数组初始化

  数组中每一个元素对象被创建时,系统都会调用类构造函数初始化该对象。

通过初始化列表赋值。
例:Point a[2]={Point(1,2),Point(3,4)};

  如果没有为数组元素指定显式初始值,数组元素便使用默认值初始化(调用默认构造函数)。

数组元素所属类的构造函数

  当数组中每一个对象被删除时,系统都要调用一次析构函数。

//Point.h

#ifndef _POINT_H
#define _POINT_H

class Point { //类的定义

public: //外部接口
	Point();
	Point(int x, int y);
	~Point();
	void move(int newX,int newY);
	int getX() const { return x; }
	int getY() const { return y; }
	static void showCount(); //静态函数成员

private: //私有数据成员
	int x, y;
};
#endif //_POINT_H
//Point.cpp

#include <iostream>
#include "Point.h"
using namespace std;

Point::Point() : x(0), y(0) {
	cout << "Default Constructor called." << endl;
}

Point::Point(int x, int y) : x(x), y(y) {
	cout << "Constructor called." << endl;
}

Point::~Point() {
	cout << "Destructor called." << endl;
}

void Point::move(int newX,int newY) {
	cout << "Moving the point to (" << newX << ", " << newY << ")" << endl;
	x = newX;
	y = newY;

}
//6-3.cpp
#include "Point.h"
#include <iostream>
using namespace std;

int main() {
	cout << "Entering main..." << endl;
	Point a[2];

	for(int i = 0; i < 2; i++)
		a[i].move(i + 10, i + 20);
		cout << "Exiting main..." << endl;

return 0;
}

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!