CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Threaded View

  1. #5
    Join Date
    Jan 2009
    Posts
    16

    Re: Issues overloading [] operator

    EDIT: Ok I figured it out - I called (*poly2)[1] -- now all that remains is how to fix my class so that calling poly[2] works correctly

    Ok, here is class Polynomial with all 3 of its constructors. This file is classes.h

    Code:
    class Polynomial{
    	int *coeff; //array of coefficients
    	int nCoeff;
    
    public:
    	//Polynomial with constant
    	Polynomial(const int a = 0);
    	//Polynomial degree n, array(n + 1)
    	Polynomial(const int, int *);
    	//copy constructor
    	Polynomial(const Polynomial &);
    	//deconstructor
    	~Polynomial();
    
    	//getDegree returns degree of polynomial
    	const int getDegree();
    	
    	//overloading array operator
    	int operator[](unsigned int index);
    };
    
    /*
    		CONSTRUCTORS
    */
    Polynomial::Polynomial(const int a){
    	coeff = new int[1];
    	coeff[0] = a;
    	nCoeff = 1;
    }
    
    Polynomial::Polynomial(const int a, int *c){
    	nCoeff = a + 1;
    	coeff = new int[a+1];
    
    	for (int i = 0; i < (a+1); ++i){
    		coeff[i] = c[i];
    	}
    }
    
    Polynomial::Polynomial(const Polynomial &p){
    	//they're not the same
    	if (this != &p){
    		delete []coeff;
    		coeff = p.coeff;
    		nCoeff = p.nCoeff;
    	}
    }
    
    
    /*
    		GETDEGREE()
    */
    const int Polynomial::getDegree(){
    	int i = nCoeff - 1;
    	while (coeff[i] == 0) --i;
    	return i;
    }
    
    //array operator
    int Polynomial::operator[](unsigned int index){
    	return coeff[index];
    }
    And here is the main procedure for testing:

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <conio.h>
    #include "classes.h"
    
    using namespace std;
    
    int main(){
    	int coeff[4] = {1, 3};
    	int coefft[4] = {6, 2};
    	Polynomial * poly = new Polynomial(1, coefft);	
    	Polynomial * poly2 = new Polynomial(1, coeff);
    	cout << *poly2[1]; //*** line
    	delete poly;
    	delete poly2;
    	return 0;
    }
    *** line gives me an error of illegal indirection - the issue I'm having is if I take the * out of *poly[1] I get an access violation when getDegree() is called - as a matter of fact I have no idea why getDegree is even being called!
    Last edited by Lang; March 4th, 2009 at 11:01 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured