📄 07_07.cpp
字号:
// 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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -