C++中关于重载[]和() = 运算符

algorain

关于重载[]和() = 运算符,平时书上教的都是重载个+,-,*,/,什么的,直接operator+符合,然后一写代码就可以,但有的时候会遇到比较复杂的,就像[],可以用来重载一个一维数组,或者二维数组,想要研究的可以重新写一写,可以和我交流。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "iostream"
using namespace std;
class Array2
{
public:
Array2(int m, int n)
{
p= new int*[m];
for (int i = 0; i < m; i++)
p[i] = new int[n];
};
Array2() :p(NULL){};
Array2 & operator =(const Array2 &arr)
{
if (p == arr.p) return *this;
if (p != NULL) delete[]p;
p = arr.p;
return *this;
};
int * & operator [](const int & m)
{
return p[m]; //关键在于返回的类型为int *即可
};
int & operator ()(const int &m, int const & n)
{
return p[m][n];
}
private:
int **p;
};
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;
}

  • Title: C++中关于重载[]和() = 运算符
  • Author: algorain
  • Created at: 2017-02-03 12:44:47
  • Updated at: 2023-05-14 21:39:50
  • Link: http://www.rain1024.com/2017/02/03/c-article0012/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments
On this page
C++中关于重载[]和() = 运算符