运算符重载编程题3(C++程序设计第4周)
来源:互联网 发布:centos如何安装deb文件 编辑:程序博客网 时间:2024/05/16 10:03
问题描述
写一个二维数组类 Array2,使得下面程序的输出结果是:
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
程序:
#include <iostream>#include <cstring>using namespace std;// 在此处补充你的代码int main() { Array2 a(3,4); int i,j; for( i = 0;i < 3; ++i ) for( j = 0; j < 4; j ++ ) a[i][j] = i * 4 + j; for( i = 0;i < 3; ++i ) { for( j = 0; j < 4; j ++ ) { cout << a(i,j) << ","; } cout << endl; } cout << "next" << endl; Array2 b; b = a; for( i = 0;i < 3; ++i ) { for( j = 0; j < 4; j ++ ) { cout << b[i][j] << ","; } cout << endl; } return 0;}
输入
无
输出
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
样例输入
无
样例输出
0,1,2,3,4,5,6,7,8,9,10,11,next0,1,2,3,4,5,6,7,8,9,10,11,
提示
提交作业时只提交补充的代码
源码
#include <iostream>#include <cstring>using namespace std;// 在此处补充你的代码class Array2{private: int row;//数组行数 int column;//数组列数 int* ptr;//指向二维数组的指针public: Array2() { ptr = NULL; } Array2(int paraRow, int paraColumn):row(paraRow),column(paraColumn) { ptr = new int[row * column]; } Array2(Array2& a):row(a.row),column(a.column) { ptr = new int[row * column]; memcpy(ptr, a.ptr, sizeof(int)*row*column); } Array2& operator= (const Array2 &a) { if (ptr) delete[] ptr; row = a.row; column = a.column; ptr = new int[row * column]; memcpy(ptr, a.ptr, sizeof(int)*row*column); return *this; } ~Array2() { if (ptr) delete[] ptr; } int* operator [] (int i) { return ptr + i*column;//重载的实际上是第二维的[], 第一维的[]直接调用int型一维数组的定义 } int& operator() (int i, int j) { return ptr[i*column + j]; }};int main() { Array2 a(3,4); int i,j; for( i = 0;i < 3; ++i ) for( j = 0; j < 4; j ++ ) a[i][j] = i * 4 + j; for( i = 0;i < 3; ++i ) { for( j = 0; j < 4; j ++ ) { cout << a(i,j) << ","; } cout << endl; } cout << "next" << endl; Array2 b; b = a; for( i = 0;i < 3; ++i ) { for( j = 0; j < 4; j ++ ) { cout << b[i][j] << ","; } cout << endl; } return 0;}
0 0
- 运算符重载编程题3(C++程序设计第4周)
- 运算符重载-编程题#3(C++程序设计第4周)
- 运算符重载编程题1(C++程序设计第4周)
- 运算符重载编程题2(C++程序设计第4周)
- 运算符重载-编程题#1(C++程序设计第4周)
- 运算符重载-编程题#2(C++程序设计第4周)
- C02-程序设计基础提高班(C++)第11周上机任务-运算符重载
- 运算符重载 编程题#2(Coursera 程序设计与算法 专项课程3 C++程序设计;重载:& operator-)
- * 运算符重载 编程题#4:大整数的加减乘除(Coursera 程序设计与算法;重载:& operator <<, & operator >>, +, -, *, /)
- C++程序设计-第8周 运算符的重载
- MOOC清华《面向对象程序设计》第3章编程题第1题:重载函数运算符以封装排序算法
- MOOC清华《面向对象程序设计》第3章编程题第2题:重载下标运算符以统计分段人数
- 运算符重载 编程题#1(Coursera 程序设计与算法 专项课程3 C++程序设计;重载:& operator =, operator =)
- 运算符判定(C程序设计进阶第9周)
- C++程序设计-第9周 运算符的重载(之二)
- 第2.6节:运算符重载(C++)
- 谭浩强C++程序设计第10章运算符重载
- C++程序设计 - Week 4 运算符重载
- 【UESTC】2015 UESTC Training for Data Structures
- 运算符重载编程题2(C++程序设计第4周)
- ubuntu 安装jdk7小结
- LeetCode 118:Pascal's Triangle
- Composer
- 运算符重载编程题3(C++程序设计第4周)
- 图形验证码最佳实践
- 利用joomla 3.2.0 – 3.4.4 注入漏洞到getshell
- 阿里巴巴开源项目 Druid 负责人温少访谈
- 个人总结面试题
- 实时公交位置系统的实现
- 大整数的加减乘除(C++程序设计第4周)
- 【jQuery】:last-child子元素过滤选择器
- ES6个人学习整理(五)——Set和Map