C++之对象数组

对象数组的定义与访问

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

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

对象数组初始化

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

通过初始化列表赋值。
例: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;
}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值