Thread: Operator Overloading

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    109

    Operator Overloading

    Hi, I have made an IntArray class with overloaded operators. I have been desperately trying to fix the program. There is a driver with 20 tests. Before I was able to go through all twenty tests but the contents of the array were almost always -842150451. After many hours of messing around with it and messing around with the operators I can no longer get through all twenty tests because a runtime error pops up on the sixth test that says:
    TestProgram.exe has encountered a problem.
    and now the numbers are almost all -8. I have managed to make my program worse than before. I have been coding for many hours and I am making frequent mistakes. I have to get this done soon and I do not know what is wrong. Right now I think there is a problem with some of the constructors, the [] operators and the ostream/istream operators. Please somebody help me! I am desperate. Below is my code and I will post a second post with the driver code. Can somebody please help me so that all the tests execute and so the output is not random numbers. I need to fix the many flaws in my code. Please help! Thank you.

    Code:
    #include <iostream>
    #include "intarray.h"
    #include "iadrv.h"
    using namespace std;
    using std::strcpy;
    using std::strlen;
    #include <iomanip>
    using std::setw;
    
    
    IntArray::IntArray(void): start(0), finish(9)
    {
    	CreateArray(finish);
    	parray[10];
    	cout<< "constructor begin" << endl;
    }
    
    IntArray::IntArray(IntArray &rhs): parray(0), start(rhs.start), finish(rhs.finish)
    {
    	CreateArray(rhs.size);
    	for ( int i = rhs.low(); i <= rhs.high(); i++ )
    		parray[i] = rhs.parray[i];
    	cout<< "&rhs initiate" << endl;
    }
    IntArray::IntArray(int theStart, int theFinish): parray(0), start(theStart), finish(theFinish)
    {
    	if(start > finish)
    	{
    	cout<< "There is an error with the array" << endl;
    	start = theStart;
    	finish = theFinish;
    	}
    	else
    	{
    	CreateArray(finish - start + 1);
    	cout<< "constructor called"<< endl;
    	}
    
    }
    
    int IntArray::translateIndexToZeroBased(int index)
    {
    	index = index - low();
    	return index;
    }
    
    int& IntArray::operator [](int index)
    {
    	static int sink;
    	int zerobasedindex = translateIndexToZeroBased(index);
    	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	{
    		cout<< "Problem with index (less than 0)" << endl;
    		return sink;
    	}
    
    	else
    	{
    		CreateArray(index);
    
    	}
    	return parray[zerobasedindex];
    }
    
    const int& IntArray::operator [](int index) const
    {
    	static int sink;
    	int zerobasedindex = 10;
    	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	{
    		cout<< "Problem with index (l)" << endl;
    		return sink;
    	}
    	return parray[zerobasedindex];
    }
    
    IntArray::IntArray(int anarray[], int amount): parray(0), size(amount), start(0), finish(amount - 1)
    {
    	CreateArray(amount);
    	for(int i = start; i <= finish; i++)
    		parray[i] = anarray[i];
    
    }
    
    
    IntArray::IntArray(int theSize): parray(0), size(theSize), start(0), finish(theSize -1)
    {
    	CreateArray(size);
    	for(int i = start; i <= finish; i++)
    		parray[i] = i * 10;
    
    }
    
    IntArray::~IntArray()
    {
    	delete []parray;
    }
    
    void IntArray::CreateArray(int theSize)
    {
    	parray = NULL;
    	size = theSize;
    	parray = new int[size];
    }
    
    int IntArray::low()
    {
    	return theStart;
    }
    
    int IntArray::high()
    {
    	return theFinish;
    }
    
    
    
    void IntArray::setName(const char* aname)
    {
    	name = new char[strlen(aname + 1)];
    	strcpy(name, aname);
    }
    
    bool IntArray::operator ==(IntArray &other)
    {
    	if(*this != other)
    	return false;
    	for(int k = 0; k < size; k++)
    		if( parray[k] != other.parray[k])
    			return false;
    	return true;
    }
    
    bool IntArray::operator !=(IntArray &other)
    {
    	return !(this == &other);
    }
    
    IntArray &IntArray::operator =(const IntArray &rhs)
    {
    	if(this == &rhs)
    		return *this;
    	else
    	{
    		delete []parray;
    		size = rhs.size;
    		parray = new int[size];
    		for(int i = start; i<size ; i++)
    			parray[i] = rhs.parray[i];
    	}
    	return *this;
    }
    
    
    IntArray operator+ (IntArray& start, IntArray& finish)
    {
    	int *array;
    	array = new int[start.size + finish.size];
    	for(int i = 0; i < start.size; i++)
    		array [i] = start.parray [i];
    	for(int k = start.size; k < start.size + finish.size; k++)
    		array [k] = finish.parray [k - start.size];
    	IntArray temp(array, start.size + finish.size);
    	delete []array;
    	return temp;
    }
    
    IntArray& IntArray::operator+= (IntArray& add)
    {
    	delete []parray;
    	size = add.size;
    	parray = new int[size];
    	for(int k = 0; k< size ; k++)
    		parray[k] += add.parray[k];
    	cout<< "Success!" << endl;
    	return *this;
    }
    
    istream& operator>>(istream& input, IntArray& a)
       {
     
       
       input >> a.size;
       
       
       delete []a.parray;
       
       a.parray = new int [a.size];
       
    
       
       for (int n = a.low(); n <= a.high(); n++)
          input >> a[n];
    			   
       
       return input;
       }
    ostream& operator<<(ostream& output, IntArray& a )
      {
    
       
       for (int n = a.low(); n <= a.high(); n++)
          output << a[n] << endl;
    			   
        
       return output;
       }
    	
    #ifndef _IntArray_H
    #define _IntArray_H
    
    #include <iostream>
    #include "iadrv.h"
    using std::ostream;
    using std::istream;
    
    class IntArray
    {
    
    	friend ostream &operator<<(ostream &output, IntArray &a);
    	friend istream &operator>>(istream &input, IntArray &a);
    
    public:
    	IntArray();
    	IntArray(IntArray &);
    	IntArray(int start, int finish);
    	IntArray(int anarray[], int amount);
    	IntArray(int theSize);
    	~IntArray();
    	int& operator[](int index);
    	const int& operator[] (int index) const;
    	int high();
    	int low();
    	void setName(const char* name);
    	int translateIndexToZeroBased(int index);
    	IntArray& operator= (const IntArray &rhs);	
    	IntArray& operator+= (IntArray& add); 
        friend IntArray operator+ (IntArray& start, IntArray& finish);
    	bool operator!= (IntArray &other);
    	bool operator== (IntArray &other);
    protected:
    	void CreateArray(int theSize);
    
    
    private:
    	int start;
    	int finish;
    	int size;
    	int *parray;
    	int index;
    	int anarray;
    	int amount;
    	char* name;
    	int theSize;
    	int theStart;
    	int theFinish;
    };
    
    #endif

  2. #2
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    Code:
    IntArray::IntArray(void): start(0), finish(9)
    {
    [edit1]	CreateArray(finish); don't you mean finish + 1?  [/edit1]
    	parray[10]; Are you just asking for an access violation? This does nothing
    	cout<< "constructor begin" << endl;
    }
    [edit2]What are you trying to accomplish with start and finish anyway? Shouldn't the start always be 0?[/edit2]
    [edit3]
    Code:
    IntArray::IntArray(IntArray &rhs): parray(0), start(rhs.start), finish(rhs.finish)
    {
    	CreateArray(rhs.size);
    	for ( int i = rhs.low(); i <= rhs.high(); i++ )
    		parray[i - rhs.low()] = rhs.parray[i - rhs.low()]; //your original code only worked with low being zero
    	cout<< "&rhs initiate" << endl;
    }
    [/edit3]
    [edit4]
    Code:
    IntArray::IntArray(int theStart, int theFinish): parray(0), start(theStart), finish(theFinish)
    {
    	if(start > finish)
    	{
    	cout<< "There is an error with the array" << endl;
    	start = theStart; This doesn't change anything.  Don't you mean to switch them? start = theFinish; finish = theStart; then you continue like normal
    	finish = theFinish;
    	}
    [/edit4]
    [edit5]
    Code:
    int& IntArray::operator [](int index)
    {
    	static int sink;
    	int zerobasedindex = translateIndexToZeroBased(index);
    	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	{
    		cout<< "Problem with index (less than 0)" << endl;
    		return sink; how is this different than returning 0?
    	}
    
    	else
    	{
    		CreateArray(index); // What? No.
    
    	}
    	return parray[zerobasedindex];
    }
    
    const int& IntArray::operator [](int index) const
    {
    	static int sink;
    	int zerobasedindex = 10; // translateIndexToZeroBased(index)
    	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	{
    		cout<< "Problem with index (l)" << endl;
    		return sink;
    	}
    	return parray[zerobasedindex];
    }
    [/edit5]
    Last edited by Brad0407; 07-23-2007 at 10:25 PM.
    Don't quote me on that... ...seriously

  3. #3
    Registered User
    Join Date
    Jul 2007
    Posts
    109
    I forgot to delete the parray[10] and I will remove that right away.

    Start can be a negative number. the indices can be (-3, 6) where start = -3 and finish = 6.

    for your third edit. No, I do not want to switch them that would be pointless. I want to simulate a halt if that happens and that is what I did there.

    for edit four: how should I change the code where you commented // what? no.

    The fifth edit is an error. because its a constant so can't be changed.

    Thanks. Can you find any other errors?

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    109
    here is the driver:

    Code:
    #ifndef _IADRV_H
    
    #define _IADRV_H
    
     
    
    #include "intarray.h"
    
     
    
    int main();
    
    void test1();
    
    void test2();
    
    void test3();
    
    void test4();
    
    void test5();
    
    void test6();
    
    void test7();
    
    void test8();
    
    void test9();
    
    void test10();
    
    void test11();
    
    void test12();
    
    void test13();
    
    void test14();
    
    void test15();
    
    void test16();
    
    void test17();
    
    void test18();
    
    void test19();
    
    void test20();
    
    void wait();
    
     
    
    #endif
    
    
    
    // iadrv.cpp - driver program for testing IntArray class
    
     
    
    #include <iostream>
    
    #include <iomanip>
    
    #include <fstream>
    
    #include <stdlib.h>
    
    #include "iadrv.h"
    
    #include "intarray.h"
    
     
    
    using namespace std;
    
     
    
    ofstream csis;
    
     
    
    int main() {
    
        csis.open("csis.dat");
    
        test1();
    
        test2();
    
        test3();
    
        test4();
    
        test5();
    
        test6();
    
        test7();
    
        test8();
    
        test9();
    
        test10();
    
        test11();
    
        test12();
    
        test13();
    
        test14();
    
        test15();
    
        test16();
    
        test17();
    
        test18();
    
        test19();
    
        test20();
    
        csis.close();
    
    }
    
     
    
    void test1() {
    
        system("cls");
    
        cout << "1. Array declared with single integer: IntArray a(10);" << endl << endl;
    
        csis << "1. Array declared with single integer: IntArray a(10);" << endl << endl;
    
        IntArray a(10);
    
        for(int i = a.low(); i <= a.high(); i++)
    
            a[i] = i * 10;
    
        a.setName("a");
    
        cout << a << endl;
    
        csis << a << endl;
    
        wait();
    
    }
    
     
    
    void test2() {
    
        system("cls");
    
        cout << "2. Array declared with two integers: IntArray b(-3, 6);" << endl << endl;
    
        csis << "2. Array declared with two integers: IntArray b(-3, 6);" << endl << endl;
    
        IntArray b(-3, 6);
    
        for(int i = b.low(); i <= b.high(); i++)
    
            b[i] = i * 10;
    
        b.setName("b");
    
        cout << b << endl;
    
        csis << b << endl;
    
        wait();
    
    }
    
     
    
    void test3() {
    
        system("cls");
    
        cout << "3. Array declared with two integers: IntArray c(6, 8);" << endl << endl;
    
        csis << "3. Array declared with two integers: IntArray c(6, 8);" << endl << endl;
    
        IntArray c(6, 8);
    
        for(int i = c.low(); i <= c.high(); i++)
    
            c[i] = i * 10;
    
        c.setName("c");
    
        cout << c << endl;
    
        csis << c << endl;
    
        wait();
    
    }
    
     
    
    void test4() {
    
        system("cls");
    
        cout << "4. Array declared with two identical integers: IntArray d(5, 5);" << endl << endl;
    
        csis << "4. Array declared with two identical integers: IntArray d(5, 5);" << endl << endl;
    
        IntArray d(5, 5);
    
        for(int i = d.low(); i <= d.high(); i++)
    
            d[i] = i * 10;
    
        d.setName("d");
    
        cout << d << endl;
    
        csis << d << endl;
    
        wait();
    
    }
    
     
    
    void test5() {
    
        system("cls");
    
        cout << "5. Array declared with no integers: IntArray z;" << endl << endl;
    
        csis << "5. Array declared with no integers: IntArray z;" << endl << endl;
    
        IntArray z;
    
        for(int i = z.low(); i <= z.high(); i++)
    
            z[i] = i * 10;
    
        z.setName("z");
    
        cout << z << endl;
    
        csis << z << endl;
    
        wait();
    
    }
    
     
    
    void test6() {
    
        system("cls");
    
        cout << "6. Array declared with another object of type IntArray: IntArray c(6, 8);" << endl;
    
        cout << "                                                        Intarray e(c);"    << endl << endl;
    
        csis << "6. Array declared with another object of type IntArray: IntArray c(6, 8);" << endl;
    
        csis << "                                                        Intarray e(c);"    << endl << endl;
    
        IntArray c(6, 8);
    
        for(int i = c.low(); i <= c.high(); i++)
    
            c[i] = i * 10;
    
        c.setName("c");
    
        cout << c << endl;
    
        csis << c << endl;
    
        IntArray e(c);
    
        e.setName("e");
    
        cout << e << endl;   
    
        csis << e << endl;
    
        wait();
    
    }
    
     
    
    void test7() {
    
        system("cls");
    
        cout << "7. Array assigned to another array with different indices: IntArray f(1, 4);"  << endl;
    
        cout << "                                                           IntArray g(5, 8);"  << endl;
    
        cout << "                                                           f = g;"             << endl << endl;
    
        csis << "7. Array assigned to another array with different indices: IntArray f(1, 4);"  << endl;
    
        csis << "                                                           IntArray g(5, 8);"  << endl;
    
        csis << "                                                           f = g;"             << endl << endl;
    
        IntArray f(1, 4);
    
        for(int i = f.low(); i <= f.high(); i++)
    
            f[i] = i * 10;
    
        f.setName("f");
    
        cout << f << endl;
    
        csis << f << endl;
    
        IntArray g(5, 8);
    
        for(int i = g.low(); i <= g.high(); i++)
    
            g[i] = i * 10;
    
        g.setName("g");
    
        cout << g << endl;
    
        csis << g << endl;
    
        wait();
    
        system("cls");
    
        f = g;
    
        cout << f << endl;
    
        cout << g << endl;
    
        csis << f << endl;
    
        csis << g << endl;
    
        wait();
    
    }
    
     
    
    void test8() {
    
        system("cls");
    
        cout << "8. Multiple array assignment with different indices: IntArray j(3, 6);"  << endl;
    
        cout << "                                                     IntArray k(6, 9);"  << endl;
    
        cout << "                                                     IntArray l(1, 4);"  << endl;
    
        cout << "                                                     j = k = l;"         << endl << endl;
    
        csis << "8. Multiple array assignment with different indices: IntArray j(3, 6);"  << endl;
    
        csis << "                                                     IntArray k(6, 9);"  << endl;
    
        csis << "                                                     IntArray l(1, 4);"  << endl;
    
        csis << "                                                     j = k = l;"         << endl << endl;
    
        IntArray j(3, 6);
    
        for(int i = j.low(); i <= j.high(); i++)
    
            j[i] = i * 10;
    
        j.setName("j");
    
        cout << j << endl;
    
        csis << j << endl;
    
        IntArray k(6, 9);
    
        for(int i = k.low(); i <= k.high(); i++)
    
            k[i] = i * 10;
    
        k.setName("k");
    
        cout << k << endl;
    
        csis << k << endl;
    
        IntArray l(1, 4);
    
        for(int i = l.low(); i <= l.high(); i++)
    
            l[i] = i * 10;
    
        l.setName("l");
    
        cout << l << endl;
    
        csis << l << endl;
    
        wait();
    
        system("cls");
    
        j = k = l;
    
        cout << j << endl;
    
        cout << k << endl;
    
        cout << l << endl;
    
        csis << j << endl;
    
        csis << k << endl;
    
        csis << l << endl;
    
        wait();
    
    }
    
     
    
    void test9() {
    
        system("cls");
    
        cout << "9. Overloaded equality operator (identical elements): IntArray m(3, 7);"  << endl;
    
        cout << "                                                      IntArray n(1, 5);"  << endl;
    
        cout << "                                                      m == n"             << endl << endl;
    
        csis << "9. Overloaded equality operator (identical elements): IntArray m(3, 7);"  << endl;
    
        csis << "                                                      IntArray n(1, 5);"  << endl;
    
        csis << "                                                      m == n"             << endl << endl;
    
        IntArray m(3, 7);
    
        for(int i = m.low(); i <= m.high(); i++)
    
            m[i] = i * 10;
    
        m.setName("m");
    
        cout << m << endl;
    
        csis << m << endl;
    
        IntArray n(1, 5);
    
        for(int i = n.low(); i <= n.high(); i++)
    
            n[i] = i * 10;
    
        n.setName("n");
    
        cout << n << endl;
    
        csis << n << endl;
    
        wait();
    
        system("cls");
    
        m = n;
    
        cout << m << endl;
    
        cout << n << endl;
    
        cout << "Returns " << (m == n ? "True." : "False.") << endl << endl;
    
        csis << m << endl;
    
        csis << n << endl;
    
        csis << "Returns " << (m == n ? "True." : "False.") << endl << endl;
    
        wait();
    
    }
    
     
    
    void test10() {
    
        system("cls");
    
        cout << "10. Overloaded equality operator (different elements): IntArray o(3, 7);"  << endl;
    
        cout << "                                                       IntArray p(1, 5);"  << endl;
    
        cout << "                                                       o == p"             << endl << endl;
    
        csis << "10. Overloaded equality operator (different elements): IntArray o(3, 7);"  << endl;
    
        csis << "                                                       IntArray p(1, 5);"  << endl;
    
        csis << "                                                       o == p"             << endl << endl;
    
        IntArray o(3, 7);
    
        for(int i = o.low(); i <= o.high(); i++)
    
            o[i] = i * 10;
    
        o.setName("o");
    
        cout << o << endl;
    
        csis << o << endl;
    
        IntArray p(1, 5);
    
        for(int i = p.low(); i <= p.high(); i++)
    
            p[i] = i * 10;
    
        p.setName("p");
    
        cout << p << endl;
    
        cout << "Returns " << (o == p ? "True." : "False.") << endl << endl;
    
        csis << p << endl;
    
        csis << "Returns " << (o == p ? "True." : "False.") << endl << endl;
    
        wait();
    
    }
    
     
    
    void test11() {
    
        system("cls");
    
        cout << "11. Overloaded equality operator (different size arrays): IntArray q(1, 3);"  << endl;
    
        cout << "                                                          IntArray r(1, 4);"  << endl;
    
        cout << "                                                          q == r;"    << endl << endl;
    
        csis << "11. Overloaded equality operator (different size arrays): IntArray q(1, 3);"  << endl;
    
        csis << "                                                          IntArray r(1, 4);"  << endl;
    
        csis << "                                                          q == r;"    << endl << endl;
    
        IntArray q(1, 3);
    
        for(int i = q.low(); i <= q.high(); i++)
    
            q[i] = i * 10;
    
        q.setName("q");
    
        cout << q << endl;
    
        csis << q << endl;
    
        IntArray r(1, 4);
    
        for(int i = r.low(); i <= r.high(); i++)
    
            r[i] = i * 10;
    
        r.setName("r");
    
        cout << r << endl;
    
        cout << "Returns " << (q == r ? "True." : "False.") << endl << endl;
    
        csis << r << endl;
    
        csis << "Returns " << (q == r ? "True." : "False.") << endl << endl;
    
        wait();
    
    }
    
     
    
    void test12() {
    
        system("cls");
    
        cout << "12. Overloaded inequality operator (identical elements): IntArray s(3, 7);" << endl;
    
        cout << "                                                         IntArray t(1, 5);" << endl;
    
        cout << "                                                         s != t;"           << endl << endl;
    
        csis << "12. Overloaded inequality operator (identical elements): IntArray s(3, 7);" << endl;
    
        csis << "                                                         IntArray t(1, 5);" << endl;
    
        csis << "                                                         s != t;"           << endl << endl;
    
        IntArray s(3, 7);
    
        for(int i = s.low(); i <= s.high(); i++)
    
            s[i] = i * 10;
    
        s.setName("s");
    
        cout << s << endl;
    
        csis << s << endl;
    
        IntArray t(1, 5);
    
        for(int i = t.low(); i <= t.high(); i++)
    
            t[i] = i * 10;
    
        t.setName("t");
    
        cout << t << endl;
    
        csis << t << endl;
    
        wait();
    
        system("cls");
    
        s = t;
    
        cout << s << endl;
    
        cout << t << endl;
    
        cout << "Returns " << (s != t ? "True." : "False.") << endl << endl;
    
        csis << s << endl;
    
        csis << t << endl;
    
        csis << "Returns " << (s != t ? "True." : "False.") << endl << endl;
    
        wait();
    
    }
    
     
    
    void test13() {
    
        system("cls");
    
        cout << "13. Overloaded inequality operator (different elements): IntArray u(3, 7);" << endl;
    
        cout << "                                                         IntArray v(1, 5);" << endl;
    
        cout << "                                                         u != v;"           << endl << endl;
    
        csis << "13. Overloaded inequality operator (different elements): IntArray u(3, 7);" << endl;
    
        csis << "                                                         IntArray v(1, 5);" << endl;
    
        csis << "                                                         u != v;"           << endl << endl;
    
        IntArray u(3, 7);
    
        for(int i = u.low(); i <= u.high(); i++)
    
            u[i] = i * 10;
    
        u.setName("u");
    
        cout << u << endl;
    
        csis << u << endl;
    
        IntArray v(1, 5);
    
        for(int i = v.low(); i <= v.high(); i++)
    
            v[i] = i * 10;
    
        v.setName("v");
    
        cout << v << endl;
    
        cout << "Returns " << (u != v ? "True." : "False.") << endl << endl;
    
        csis << v << endl;
    
        csis << "Returns " << (u != v ? "True." : "False.") << endl << endl;
    
        wait();
    
    }
    
     
    
    void test14() {
    
        system("cls");
    
        cout << "14. Overloaded inequality operator (different size arrays): IntArray w(1, 3);" << endl;
    
        cout << "                                                            IntArray x(1, 4);" << endl;
    
        cout << "                                                            w != x;"           << endl << endl;
    
        csis << "14. Overloaded inequality operator (different size arrays): IntArray w(1, 3);" << endl;
    
        csis << "                                                            IntArray x(1, 4);" << endl;
    
        csis << "                                                            w != x;"           << endl << endl;
    
        IntArray w(1, 3);
    
        for(int i = w.low(); i <= w.high(); i++)
    
            w[i] = i * 10;
    
        w.setName("w");
    
        cout << w << endl;
    
        csis << w << endl;
    
        IntArray x(1, 4);
    
        for(int i = x.low(); i <= x.high(); i++)
    
            x[i] = i * 10;
    
        x.setName("x");
    
        cout << x << endl;
    
        cout << "Returns " << (w != x ? "True." : "False.") << endl << endl;
    
        csis << x << endl;
    
        csis << "Returns " << (w != x ? "True." : "False.") << endl << endl;
    
        wait();
    
    }
    
     
    
    void test15() {
    
        system("cls");
    
        cout << "15. Sum of two arrays assigned to third array: IntArray a(1, 5);"   << endl;
    
        cout << "                                               IntArray b(4, 8);"   << endl;
    
        cout << "                                               IntArray c = a + b;" << endl << endl;
    
        csis << "15. Sum of two arrays assigned to third array: IntArray a(1, 5);"   << endl;
    
        csis << "                                               IntArray b(4, 8);"   << endl;
    
        csis << "                                               IntArray c = a + b;" << endl << endl;
    
        IntArray a(1, 5);
    
        for(int i = a.low(); i <= a.high(); i++)
    
            a[i] = i * 10;
    
        a.setName("a");
    
        cout << a << endl;
    
        csis << a << endl;
    
        IntArray b(4, 8);
    
        for(int i = b.low(); i <= b.high(); i++)
    
            b[i] = i * 10;
    
        b.setName("b");
    
        cout << b << endl;
    
        csis << b << endl;
    
        wait();
    
        system("cls");
    
        IntArray c = a + b;
    
        c.setName("c");
    
        cout << c << endl;
    
        csis << c << endl;
    
        wait();
    
    }
    
     
    
    void test16() {
    
        system("cls");
    
        cout << "16. Sum of two arrays assigned to first array: IntArray d(10, 13);" << endl;
    
        cout << "                                               IntArray e(30, 33);" << endl;
    
        cout << "                                               d += e;"             << endl << endl;
    
        csis << "16. Sum of two arrays assigned to first array: IntArray d(10, 13);" << endl;
    
        csis << "                                               IntArray e(30, 33);" << endl;
    
        csis << "                                               d += e;"             << endl << endl;
    
        IntArray d(10, 13);
    
        for(int i = d.low(); i <= d.high(); i++)
    
            d[i] = i * 10;
    
        d.setName("d");
    
        cout << d << endl;
    
        csis << d << endl;
    
        IntArray e(30, 33);
    
        for(int i = e.low(); i <= e.high(); i++)
    
            e[i] = i * 10;
    
        e.setName("e");
    
        cout << e << endl;
    
        csis << e << endl;
    
        d += e;
    
        cout << d << endl;
    
        csis << d << endl;
    
        wait();
    
    }
    
     
    
    void test17() {
    
        system("cls");
    
        cout << "17. Array declared with illegal array bounds: IntArray f(5, 2);" << endl << endl;
    
        csis << "17. Array declared with illegal array bounds: IntArray f(5, 2);" << endl << endl;
    
        IntArray f(5, 2);
    
        for(int i = f.low(); i <= f.high(); i++)
    
            f[i] = i * 10;
    
        f.setName("f");
    
        cout << f << endl;
    
        csis << f << endl;
    
        wait();
    
    }
    
     
    
    void test18() {
    
        system("cls");
    
        cout << "18. Array with index out of range: IntArray g(10);"    << endl;
    
        cout << "                                   g[10] = 1;"         << endl << endl;
    
        csis << "18. Array with index out of range: IntArray g(10);"    << endl;
    
        csis << "                                   g[10] = 1;"         << endl << endl;
    
        IntArray g(10);
    
        for(int i = g.low(); i <= g.high(); i++)
    
            g[i] = i * 10;
    
        g.setName("g");
    
        cout << g << endl;
    
        csis << g << endl;
    
        g[10] = 1;
    
        wait();
    
    }
    
     
    
    void test19() {
    
        system("cls");
    
        cout << "19. Arrays with length mismatch: IntArray m(1, 4);" << endl;
    
        cout << "                                 IntArray n(2, 4);" << endl;
    
        cout << "                                 m = n;"            << endl << endl;
    
        csis << "19. Arrays with length mismatch: IntArray m(1, 4);" << endl;
    
        csis << "                                 IntArray n(2, 4);" << endl;
    
        csis << "                                 m = n;"            << endl << endl;
    
        IntArray m(1, 4);
    
        for(int i = m.low(); i <= m.high(); i++)
    
            m[i] = i * 10;
    
        m.setName("m");
    
        cout << m << endl;
    
        csis << m << endl;
    
        IntArray n(2, 4);
    
        for(int i = n.low(); i <= n.high(); i++)
    
            n[i] = i * 10;
    
        n.setName("n");
    
        cout << n << endl;
    
        csis << n << endl;
    
        wait();
    
        system("cls");
    
        m = n;
    
        cout << m << endl;
    
        cout << n << endl;
    
        csis << m << endl;
    
        csis << n << endl;
    
        wait();
    
    }
    
     
    
    void test20() {
    
        system("cls");
    
        cout << "20. Array subscript operator: IntArray o(7, 8);" << endl;
    
        cout << "                              o[7] = 25;"        << endl;
    
        cout << "                              o[8] = o[7];"      << endl << endl;
    
        csis << "20. Array subscript operator: IntArray o(7, 8);" << endl;
    
        csis << "                              o[7] = 25;"        << endl;
    
        csis << "                              o[8] = o[7];"      << endl << endl;
    
        IntArray o(7, 8);
    
        for(int i = o.low(); i <= o.high(); i++)
    
            o[i] = i * 10;
    
        o.setName("o");
    
        cout << o << endl;
    
        csis << o << endl;
    
        o[7] = 25;
    
        o[8] = o[7];
    
        cout << o << endl;
    
        csis << o << endl;
    
        wait();
    
    }
    
     
    
    void wait() {
    
        char buf;
    
     
    
        cout << "Press any key to continue." << endl;
    
        cin.get(buf);
    
    }

  5. #5
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    for your third edit. No, I do not want to switch them that would be pointless. I want to simulate a halt if that happens and that is what I did there.
    well it's pointless to assign them again. if you switched them, you could assume that the range is still correct and that the user still wants that range. For example, lowest 5, highest 1. The user wants the array to be between 1 and 5. just make lowest 1 and highest 5

    for edit four: how should I change the code where you commented // what? no.
    I am confused by why you would recreate the array. I think it should be removed competely.

    The fifth edit is an error. because its a constant so can't be changed.
    10 is a constant, yes. But the user wants to access 'index' not '10'.

    Thanks. Can you find any other errors?
    Yeah, your == and != operators need alot of correcting. I'm too tired to give good explanations and the homework policy won't let me just rewrite it for you.

    [edit]Did you write the driver program or was it given to you?[/edit]
    Last edited by Brad0407; 07-23-2007 at 11:09 PM.
    Don't quote me on that... ...seriously

  6. #6
    Registered User
    Join Date
    Jul 2007
    Posts
    109
    If the low is 5 and the high is 1 then I am instructed to simulate a halt. I should not switch them.

    "Remove completely" okay I will do that.

    How should I access index then?

    What corrections need to be made to the == and !=?

    Yes, the driver was supplied to me.

    Can you see any problems with the []operator, constructors, or i/ostream operators?

    Thanks

  7. #7
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I don't get this class. Do you create an array from say 34 to 50 and then access members using indices in range [34, 50]?

    As long as I haven't modified array contents, index == element value - so what's the use of the array? To get to an element, I first need to know the value of the element anyway?

    If I have modified the values, what do the indices 34...50 mean now?

    As to problems, for example here a.size, a.low and a.high seem to become unrelated. You created an array the size the user entered. Then you loop for some time which seems completely unrelated to the size the user entered.
    Code:
       a.parray = new int [a.size];  
       
       for (int n = a.low(); n <= a.high(); n++)
          input >> a[n];
    This has been pointed out before:
    Code:
    int& IntArray::operator [](int index)
    {
    	static int sink;
    	int zerobasedindex = translateIndexToZeroBased(index);
    	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	{
    		cout<< "Problem with index (less than 0)" << endl;
    		return sink; //wait, what good is returning an unitialized value (or is it 0)?
    	}
    
    	else
    	{
    		CreateArray(index); //You mean, array access creates a new array?
    
    	}
    	return parray[zerobasedindex];
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I'm only going to bother mentioning one error today:
    You're stream operators don't do the reverse of each other! One inputs the size, yet the other never outputs it.
    That would be rather bad if you wanted to write it to file and read it back in again.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    Why do you have start and theStart. and finish and theFinish. and size and theSize?

    This causes almost all your problems because you forget one of the pair when you are initializing and then try to use it later.

    How are the ==, !=, +, +=, >>, and << operators supposed to act. What is the ideal result of these? I need to know or I can't help you.

    Code:
    intarray.cpp
    IntArray::IntArray(void): start(0), finish(9) 
    {
    //	CreateArray(finish); This would hold 9 elements.  You need it to hold 10
    	CreateArray(finish + 1);  //Added by Brad.  This holds 10
    //	parray[10]; This does nothing.  Delete immediately
    
    	cout<< "constructor begin" << endl;
    }
    
    IntArray::IntArray(IntArray &rhs): parray(0), start(rhs.start), finish(rhs.finish)
    {
    	CreateArray(rhs.size);
    	for ( int i = rhs.low(); i <= rhs.high(); i++ )
    ///		parray[i] = rhs.parray[i]; if rhs.low isn't 0, this won't work
    		parray[i - rhs.low()] = rhs.parray[i - rhs.low()]; // Added by Brad.  
    								  // Corrects the index to Zero Based
    	cout<< "&rhs initiate" << endl;
    }
    IntArray::IntArray(int theStart, int theFinish): parray(0), start(theStart), finish(theFinish)
    {
    	if(start > finish)
    	{
    	cout<< "There is an error with the array" << endl;
    //	start = theStart;   The halt has already been caused.
    //	finish = theFinish;  These values are already set in the function heading
    	}
    	else
    	{
    	CreateArray(finish - start + 1);
    	cout<< "constructor called"<< endl;
    	}
    
    }
    
    int IntArray::translateIndexToZeroBased(int index)
    {
    	index = index - low();
    	return index;
    }
    
    int& IntArray::operator [](int index)
    {
     	static int sink;// After review, I see that this variable is necessary for return type int&
    	int zerobasedindex = translateIndexToZeroBased(index);
    //	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	if(zerobasedindex < 0 || zerobasedindex >= size) //ABB. I removed 'theSize' from the class
    	{
    	//	cout<< "Problem with index (less than 0)" << endl;
    		cout << "Problem with index (out of range)" << endl; // ABB (Added by Brad)
    									// This is a better description of the problem
    		return sink;
    	}
    
    /*	else
    	{
    		CreateArray(index); You are accessing elements not recreating the array
    
    	}*/
    	return parray[zerobasedindex];
    }
    
    const int& IntArray::operator [](int index) const
    {
    	static int sink;
    //	int zerobasedindex = 10; The user wants to access index
    	int zerobasedindex = index - start; // ABB. Correct the index to zero based
    //	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	if(zerobasedindex < 0 || zerobasedindex >= size) //ABB. I removed 'theSize' from the class
    	{
    	//	cout<< "Problem with index (l)" << endl;
    		cout << "Problem with index (out of range)" << endl; // ABB. better description
    		return sink;
    	}
    	return parray[zerobasedindex];
    }
    
    IntArray::IntArray(int anarray[], int amount): parray(0), size(amount), start(0), finish(amount - 1)
    {
    	CreateArray(amount);
    	for(int i = start; i <= finish; i++)
    		parray[i] = anarray[i];
    
    }
    
    
    IntArray::IntArray(int theSize): parray(0), size(theSize), start(0), finish(theSize -1)
    {
    	CreateArray(size);
    	for(int i = start; i <= finish; i++)
    		parray[i] = i * 10;
    }
    
    IntArray::~IntArray()
    {
    	delete []parray;
    }
    
    void IntArray::CreateArray(int theSize)
    {
    	parray = NULL;
    	size = theSize;
    	parray = new int[size];
    }
    
    int IntArray::low()
    {
    //	return theStart;
    	return start; // ABB. I removed theStart
    }
    
    int IntArray::high()
    {
    //	return theFinish;
    	return finish; // ABB. I removed theFinish
    }
    
    
    
    void IntArray::setName(const char* aname)
    {
    	name = new char[strlen(aname + 1)];
    	strcpy(name, aname);
    }
    
    bool IntArray::operator ==(IntArray &other)
    {
    //	if(*this != other) this has nothing to do wtih the contents of the arrays
    //	return false;
    	if (low() != other.low())	// ABB. Check to see that they have the same
    		return false;			// ABB. starting point
    
    	if (high() != other.high())	// ABB. Check to see that they have
    		return false;			// ABB. the same ending point
    
    	for(int k = 0; k < size; k++)
    		if( parray[k] != other.parray[k])
    			return false;
    
    	return true;
    }
    
    bool IntArray::operator !=(IntArray &other)
    {
    //	return !(this == &other); this has nothing to do with the contents of the arrays
    	if (low() != other.low())	// ABB. Check to see if they have a different
    		return true;			// ABB. starting point
    
    	if (high() != other.high())	// ABB. Check to see if they have
    		return true;			// ABB. a different ending point
    
    	for(int k = 0; k < size; k++)			// ABB
    		if( parray[k] != other.parray[k])	// ABB
    			return true;	// ABB if any of the elements are different, the arrays are different
    	return false; //ABB.  If everything is the same, return false
    }
    
    IntArray &IntArray::operator =(const IntArray &rhs)
    {
    	if(this == &rhs)
    		return *this;
    	else
    	{
    		delete []parray;
    		size = rhs.size;
    		parray = new int[size];
    	//	for(int i = start; i<size ; i++) go from 0 to size not start to size
    		for(int i = 0; i < size; i++) // ABB. goes from 0 to size
    			parray[i] = rhs.parray[i];
    
    		start = rhs.start;	// ABB. Don't forget the start and finish
    		finish = rhs.finish;	// ABB. Don't forget the start and finish
    	}
    	return *this;
    }
    Code:
    intarry.h
    class IntArray
    {
    
    	friend ostream &operator<<(ostream &output, IntArray &a);
    	friend istream &operator>>(istream &input, IntArray &a);
    
    public:
    	IntArray();
    	IntArray(IntArray &);
    	IntArray(int start, int finish);
    	IntArray(int anarray[], int amount);
    	IntArray(int theSize);
    	~IntArray();
    	int& operator[](int index);
    	const int& operator[] (int index) const;
    	int high();
    	int low();
    	void setName(const char* name);
    	int translateIndexToZeroBased(int index);
    	IntArray& operator= (const IntArray &rhs);	
    	IntArray& operator+= (IntArray& add); 
        friend IntArray operator+ (IntArray& start, IntArray& finish);
    	bool operator!= (IntArray &other);
    	bool operator== (IntArray &other);
    protected:
    	void CreateArray(int theSize);
    
    
    private:
    	int start;
    	int finish;
    	int size;
    	int *parray;
    //	int index;	not used
    //	int anarray;	not used
    //	int amount;	not used
    	char* name;
    //	int theSize;	don't need 2
    //	int theStart;	don't need 2
    //	int theFinish;	don't need 2
    };
    [edit]Of course, I haven't seen the specs for the assignment so you may need both start and theStart. In that case, I would suggest a union so that you don't have to manage both of them:

    Code:
    ...
    private:
    	union
    	{
    		int start;
    		int theStart;
    	};
    	union
    	{
    		int finish;
    		int theFinish;
    	};
    	union
    	{
    		int size;
    		int theSize;
    	};
    	...
    [/edit]
    Last edited by Brad0407; 07-24-2007 at 10:00 AM.
    Don't quote me on that... ...seriously

  10. #10
    Registered User
    Join Date
    Jul 2007
    Posts
    109
    So far I have not had any problems with the == and the != operators so I think those are working fine. I should be able to do all of the following:

    Code:
         IntArray a(10), w(10);         // Ten elements, indexed 0 to 9
    
         IntArray b(-3, 6);             // Ten elements, indexed -3 to 6
    
         IntArray c(6, 8);              // Three elements, indexed 6 to 8
    
         IntArray d(5, 5);              // Single element array, indexed at 5
    
         IntArray z;                    // Ten elements, indexed 0 to 9
    
     
    
         // high() and low() return largest and smallest legal indices
    
         for (int i = a.low(); i <= a.high(); ++i)
    
              a[i] = i * 10;            // Access just like normal array
    
     
    
         // Output array contents. Note that you will overload the << operator to do this.
    
         cout << a << endl;
    
         
    
         // The code for the overloaded << operator will look something like this:
    
         for (int i = a.low(); i <= a.high(); i++)
    
              cout << "a[" << i << "] = " << a[i] << " ";
    
     
    
         // Similar code initializes b, c, and d.
    
     
    
         IntArray e(c);                 // e is a copy of c
    
     
    
         b = a;                         // b holds copy of a's elements,
    
                                        // but indices run from -3 to 6
    
     
    
         w = a + b;                     // sum two arrays into third array
    
     
    
         w += a;                        // sum two arrays into first array
    
     
    
         a[10] = 1;                     // Runtime error: illegal index
    
                                        // Print diagnostic and halt.
    
     
    
         b = c;                         // Runtime error: lengths different
    
                                        // Print diagnostic and simulate halt.
    
     
    
         if (a == d)                    // Elements compared. No run-time error
    
              cout << "TRUE" << endl;   // if lengths don't match. != also works.
    
         else                                
    
              cout << "FALSE" << endl;
    
         }

  11. #11
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    So do the start and finish of both arrays have to match or just the size? In the code I posted, I assumed that the starts and finishes had to match.
    Don't quote me on that... ...seriously

  12. #12
    Registered User
    Join Date
    Jul 2007
    Posts
    109
    When you set two arrays equal the array size has to be the same and the indices can be different but the indices of the left hand operand is used.

  13. #13
    Registered User
    Join Date
    Jul 2007
    Posts
    109
    I get this error with this code:

    error C2662: 'IntArray::translateIndexToZeroBased' : cannot convert 'this' pointer from 'const IntArray' to 'IntArray &'

    Code:
    int& IntArray::operator [](int index)
    {
    	static int sink;
    	int zerobasedindex = translateIndexToZeroBased(index);
    	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	{
    		cout<< "Problem with index (less than 0)" << endl;
    		return sink;
    	}
    
    	return parray[zerobasedindex];
    }
    
    const int& IntArray::operator [](int index) const
    {
    	static int sink;
    	int zerobasedindex = translateIndexToZeroBased(index);
    	if(zerobasedindex < 0 || zerobasedindex >= theSize)
    	{
    		cout<< "Problem with index (l)" << endl;
    		return sink;
    	}
    	return parray[zerobasedindex];
    }

  14. #14
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by BKurosawa View Post
    I get this error with this code:

    error C2662: 'IntArray::translateIndexToZeroBased' : cannot convert 'this' pointer from 'const IntArray' to 'IntArray &'
    Probably because translateIndexToZeroBased() is not declared as a 'const' function. You can't invoke a non-const method from inside a const method. If you're going to use const on methods, you have to do it consistently, everywhere.

  15. #15
    Registered User
    Join Date
    Jul 2007
    Posts
    109
    How do I fix my [] operator then?

Popular pages Recent additions subscribe to a feed