码迷,mamicode.com
首页 > 其他好文 > 详细

实验四

时间:2019-05-20 17:38:10      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:div   通过   oid   成员   int   val   ++   pause   mic   

1.

 

 

 

2.

技术图片
#include <iostream>
using namespace std;
#include "arraylnt.h"
int main() {
    // 定义动态整型数组对象a,包含2个元素,初始值为0
    ArrayInt a(2);
    a.print();
    // 定义动态整型数组对象b,包含3个元素,初始值为6
    ArrayInt b(3, 6);
    b.print();
    // 通过对象名和下标方式访问并修改对象元素
    b[0] = 2;
    cout << b[0] << endl;
    b.print();
    system("pause");
    return 0;
}
main.cpp
技术图片
#ifndef ARRAY_INT_H
#define ARRAY_INT_H
class ArrayInt{
 public:
 ArrayInt(int n, int value=0);
 ~ArrayInt();
 int& operator [](int i);
// 补足:将运算符[]重载为成员函数的声明
// ×××
void print();
private:
int *p;
int size;
};
#endif
arrayInt.h
技术图片
#include "arraylnt.h"
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
ArrayInt::ArrayInt(int n, int value): size(n) {
p = new int[size];
if (p == nullptr) {
cout << "fail to mallocate memory" << endl;
exit(0);
}
for(int i=0; i<size; i++)
p[i] = value;
}
ArrayInt::~ArrayInt() {
delete[] p;
}
void ArrayInt::print() {
for(int i=0; i<size; i++)
cout << p[i] << " ";
cout << endl;
}
int& ArrayInt::operator[](int i){
    return p[i];
}
// 补足:将运算符[]重载为成员函数的实现
// ×××
arrayInt.cpp

技术图片

 

实验四

标签:div   通过   oid   成员   int   val   ++   pause   mic   

原文地址:https://www.cnblogs.com/changtingzao/p/10894843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!