07_07.cpp

来自「一些C++的课件和实验源代码」· C++ 代码 · 共 89 行

CPP
89
字号
// 07_07.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <conio.h>
#include <string>
#include <iostream>
using namespace std;

class IndexException {
	string msg;
public:
	IndexException(string error) {msg = error;}
	string getMessage()		{return msg;}
};

class intArray {
	int size;		// 数组大小
	int *element;	// 首地址
public:
	intArray(unsigned int size) {	// 构造函数,传入数组大小
		intArray::size = size;
		element = new int[size];
		memset(element, 0, sizeof(int) * size);
	}
	~intArray() {	// 析构函数,释放资源
		if (element) delete []element;
	}
	intArray(const intArray& a) {	// 拷贝构造函数
		size = a.size;
		element = new int[size];
		memcpy(element, a.element, sizeof(int) * size);
	}
	void operator = (const intArray& a){	// 重载'='操作符
		if (element) delete[] element;
		size = a.size;
		element = new int[size];
		memcpy(element, a.element, sizeof(int) * size);
	}
	int& operator [] (unsigned int index){	// 重载下标操作符
		if (index >= size)
			throw IndexException("out of index exception.");
		
		return element[index];
	}
	intArray operator + (const intArray& a){ // 重载'+'操作符
		if (size != a.size) 
			throw IndexException("size of two array not match.");

		intArray na(size);
		for (int i = 0; i < size; i++) {
			na.element[i] = element[i] + a.element[i];
		}
		return na;
	}
	void print() {
		for (int i = 0; i < size; i++)
			cout << element[i] << "  ";
		cout << endl;
	}

};

int main(int argc, char* argv[])
{
	intArray a(3), b(3);
	
	try {
		a[0] = 1;
		a[1] = 2;
		a[2] = 3;
		b[0] = 4;
		b[1] = 5;
		b[2] = 6;

		intArray c = a + b;
		
		a.print();
		b.print();
		c.print();
	}
	catch(IndexException e) {
		cout << e.getMessage();
	}

	getch();
	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?