operator[] overloading

I want
overloading operator[] change my cpp file!.

my header file, main function is here!

help me!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef myvector_h
#define myvector_h

#endif /* myvector_h */

class myvector{

    private:
        double * arr;
        int arrlen;
        double xpos, ypos;
    public:
        int size();
        double& operator[](int pos);

};



1
2
3
4
5
6
7
8
9
10
int main() {
    
    myvector a(2);
    myvector b(2);
    
    cout << a.size();
    
    a[0] = 0.0; a[1] = 2.0;
    b[0] = 1.0; b[1] = 2.0;
}


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
#include "myvector.h"
using namespace std;


myvector :: myvector(int size) : arrlen(size)
{
 
    arr = new double[size];
    
}

int myvector :: size(){
    int vectorsize;
    
    
    return vectorsize;
};



double& operator[](int pos) {    ///  this part
   

 return arr[pos];
}


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
#include <iostream>

using namespace std;


class myvector
{

    private:
        double * arr;
        int arrlen;
        double xpos, ypos; 

    public:
	myvector(int size); //you were missing a constructor.
        int size();
        double& operator[](int pos);

};


myvector :: myvector(int size) : arrlen(size)
{
    arr = new double[size];
}

int myvector :: size()
{
    return arrlen; //simply return arrlen. What you had before doesn't return size of array.
}// remove semi colon here

double& myvector :: operator[](int pos) //you need to use scope operator '::'.
{      
    return arr[pos];
}


//test :
int main()
{
	myvector v(10);

	for(int i=0; i< v.size(); i++)
	{
		v[i]=i;
		cout << v[i] << ' ';

	}

	return 0;
}
Last edited on
Topic archived. No new replies allowed.