作者:非妃是公主
专栏:《笔记》《C++》
个性签:顺境不惰,逆境不馁,以心制境,万事可成。——曾国藩
Myfarray.h
#pragma once
#include<iostream>
using namespace std;
class Myfarray {
private:
int m_num;
int* m_data;
public:
Myfarray(int n) :m_num(n) {
m_data = new int[n];
for (int i = 0; i < m_num; i++) {
m_data[i] = 0;
}
}
~Myfarray() {
delete[]m_data;
}
Myfarray& operator=(const Myfarray& myf);
Myfarray(const Myfarray& myf);
int& operator[](int i);
friend ostream& operator<<(ostream& os, Myfarray& myf);
friend istream& operator>>(istream& is, Myfarray& myf);
};
Myfarray.cpp
#include"myfarray.h"
ostream& operator<<(ostream& os, Myfarray& myf) {
for (int i = 0; i < myf.m_num; i++) {
os << myf.m_data[i] << " ";
}
return os;
}
istream& operator>>(istream& is, Myfarray& myf) {
for (int i = 0; i < myf.m_num; i++) {
cout << "请输入第" << i << "个元素:" << endl;
is >> myf.m_data[i];
}
return is;
}
Myfarray& Myfarray::operator=(const Myfarray& myf) {
if (&myf == this)return*this;
m_num = myf.m_num;
delete[]m_data;
m_data = new int[m_num];
for (int i = 0; i < m_num; i++) {
m_data[i] = myf.m_data[i];
}
return *this;
}
Myfarray::Myfarray(const Myfarray& myf) {
m_num = myf.m_num;
m_data = new int[m_num];
for (int i = 0; i < m_num; i++) {
m_data[i] = myf.m_data[i];
}
}
int& Myfarray::operator[](int i) {
return m_data[i];
}
main.cpp
#include"myfarray.h"
int main() {
Myfarray myf1(5);
cin >> myf1;
cout << myf1 << endl;
Myfarray myf2(7);
cin >> myf2;
cout << myf2 << endl;
Myfarray myf3(myf2);
cout << myf3 << endl;
cout << myf3[2] << endl;
system("pause");
}
有时间再来补充…