Click here to Skip to main content
15,616,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to define two operators in a class, one for an array and the other for
adding an object with array elements,
but the following code gives an error.
What is the problem?

What I have tried:

#include <iostream>
using namespace std;
class List {
		int x[3] ; 
		int y;

	public :
		void set (int a[3] )
			for ( int j = 0; j< 3; j++)
				x[j] = a[j] ; 
		void sety (int a)
		int operator [] (int k)
			if (k <0 || k >= 3)	
          { cout << "out of bound";exit (0);}
			return x[k];
		int operator + (List t)
		    int b;
		    for(int i=0;i<3;i++)
		       b = x[i]+t.y; 
		       return b;
int main()
	List ob ;
	List ob1;
	int a[3] = {10, 11, 12};
	ob.set (a);
	cout << ob[0] << endl;   //10
	cout << ob[1] << endl;   //11
	cout << ob[2] << endl;   //12
	cout << ob[3];    
	for(int i=0;i<3;i++)
Updated 26-Jul-21 3:36am
Richard MacCutchan 26-Jul-21 9:23am    
What error, and where does it occur? Please provide proper details.
k5054 26-Jul-21 9:33am    
Your Listclass compiles fine. Your main function is incomplete. This suggests that the error you are seeing is within main<code>. As Richard has said, please fill in the details.

1 solution

I successfully compiled everything before your ///... line. After that, your code ends in the middle of nowhere, but you probably know that.

I thought that a space might not be allowed after operator, before the [] and +, but evidently it is.

Note that cout << ob[3]; will cause an immediate exit. Is that the problem?
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900