GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 24-Sep-2007, 19:58
crazy_ivan crazy_ivan is offline
New Member
 
Join Date: Sep 2007
Posts: 7
crazy_ivan is on a distinguished road

Smart Array problem


Hi, for an assignment I need to do we have to write a template for a "smart array" which basically acts like a vector (IE. can tell it's beginning/end/whatever.) Since we want it to allow any type storage I used a generic template with generic values. Every function that is nessesary is written and most (but not all) are proofread. The problem that I am encountering is this: I wrote a overloaded copy assignment (operator=) to allow copy assignment for any value_type. We are given a test program to run out template against that checks if everything is satisfactory, but when I compile the code I get the following error:
error C2106: '=' : left operand must be l-value

The weird thing is that the error happens in the test program's code...not mine. I asked about this but was reasured that the test program was valid. I have re-written the operator= function about twenty different ways but for the life of me I can't figure out how to fix said error. Can anyone give me some possible hints on this?

Here is my code:

CPP / C++ / C Code:
//ssarray.h



#ifndef FILE_SSARRAY_H_INCLUDED // ifndef inclusion
#define FILE_SSARRAY_H_INCLUDED

// #include's
#include <cstdlib>  // for std::size_t
#include <algorithm> // for std::swap, std::copy

template <typename T>

class SSArray
{

public:

	//typedef's
	typedef std::size_t size_type;
	typedef T value_type;  
	

	//default ctor
	//creates new object
	SSArray()
		:size_ (10)
	{}

	SSArray(size_type sizeIn)
		:size_ (sizeIn)
	{}

	SSArray(size_type sizeIn, const value_type & valIn)
		:size_ (sizeIn), val_ (valIn)
	{
		for(int i=0; i<=size; i++)
		{
			//set all array values to val for size.
			arr[i] = val_;
		}
	}


	//copy ctor
	//copies values of arr into arbitrary otherArray
	//Pre: arr and otherArray exsist; size >=0
	//Post: otherArray contains values of arr
	SSArray(const SSArray & otherArray)
	{
		for(int i=0; i<=otherArray.size; ++i)
		{
			std::copy(arr[0], arr[size], otherArray[]);
		}
	}

	//dcor
	//destroys object
	~SSArray()
	{
		delete [] iter;
	}

//***overloaded operators***
public:

	//copy assignment
	SSArray & operator=(const SSArray & otherArray )
	{
		if(this != otherArray)
		{
			std::copy(otherArray.begin(), otherArray.end(), arr);	
		}
		return *this;
	}

	//const and non-const [] operator
	value_type operator[](int index)
	{
		return arr[index];
	}
	
	value_type operator[](int index) const
	{
		return arr[index];
	}
	
	bool & operator==(const SSArray & otherArray) const
	{
		bool equ;
		for(int i=0; i<otherArray.size(); ++i)
		{
			if(arr[i] == otherArray[i])
				equ = true;
			else
			{
				equ = false;
				break;
			}
		}
		return equ;
	}

	
	bool & operator !=(const SSArray & otherArray) const
	{
		return ( !(*this== otherArray));
	}

public:

	size_type & size() const
	{
		return size_;
	}

	value_type* begin() const
	{
		return &arr[0];
	}

	value_type* end() const
	{
		return &arr[size];
	}







public:
	//variables
	size_type size_;
	value_type val_;
	value_type arr[10];
	value_type* iter;

}; //end class ssarray

#endif //end file inclusion

Also, if it helps, here is the test program that we are given:

CPP / C++ / C Code:
// ssarray_test.cpp


#include "ssarray.h"  // For class SSArray
// Include above BEFORE system files, to make sure it works by itself
#include "ssarray.h"  // Double inclusion test

// Includes for testing package
#include <iostream>   // for std::cout, std::endl
#include <string>     // for std::string

// Includes for this testing program
#include <cstdlib>    // for std::size_t, std::ptrdiff_t


// ************************************************************************
// Testing class
// ************************************************************************


// class Tester
// For extremely simple unit testing.
// Keeps track of number of tests and number of passes.
// Use test (with success/failure parameter) to do a test.
// Get results with numTests, numPassed, numFailed, allPassed.
// Restart testing with reset.
// Invariants:
//     countTests_ == number of tests (calls to test) since last reset.
//     countPasses_ == number of times function test called with true param
//      since last reset.
//     0 <= countPasses_ <= countTests_.
//     tolerance_ >= 0.
class Tester {

// ***** Tester: ctors, dctor, op= *****
public:

    // Default ctor
    // Sets countTests_, countPasses_ to zero, tolerance_ to given value
    // Pre: None.
    // Post:
    //     numTests == 0, countPasses == 0, tolerance_ == abs(theTolerance)
    Tester(double theTolerance = 0.0000001)
        :countTests_(0),
         countPasses_(0),
         tolerance_(theTolerance >= 0 ? theTolerance : -theTolerance)
    {}

    // Compiler-generated copy ctor, copy op=, dctor are used

// ***** Tester: general public functions *****
public:

    // test
    // Handles single test, param indicates pass/fail
    // Pre: None.
    // Post:
    //     countTests_ incremented
    //     countPasses_ incremented if (success)
    //     Message indicating test name (if given)
    //      and pass/fail printed to cout
    void test(bool success,
              const std::string & testName = "")
    {
        ++countTests_;
        if (success) ++countPasses_;

        std::cout << "    ";
        if (testName != "")
        {
            std::cout << "Test: "
                      << testName
                      << " - ";
        }
        std::cout << (success ? "passed" : "********** FAILED **********")
                  << std::endl;
    }

    // ftest
    // Does single floating-point test.
    // Tests passes iff difference of first two values is <= tolerance.
    // Pre: None.
    // Post:
    //     countTests_ incremented
    //     countPasses_ incremented if (abs(val1-val2) <= tolerance_)
    //     Message indicating test name (if given)
    //      and pass/fail printed to cout
    void ftest(double val1,
               double val2,
               const std::string & testName = "")
    { test(val1-val2 <= tolerance_ && val2-val1 <= tolerance_, testName); }

    // reset
    // Resets *this to default constructed state
    // Pre: None.
    // Post:
    //     countTests_ == 0, countPasses_ == 0
    void reset()
    {
        countTests_ = 0;
        countPasses_ = 0;
    }

    // numTests
    // Returns the number of tests that have been done since last reset 
    // Pre: None.
    // Post:
    //     return == countTests_
    int numTests() const
    { return countTests_; }

    // numPassed
    // Returns the number of tests that have passed since last reset
    // Pre: None.
    // Post:
    //     return == countPasses_
    int numPassed() const
    { return countPasses_; }

    // numFailed
    // Returns the number of tests that have not passed since last reset
    // Pre: None.
    // Post:
    //     return + countPasses_ == numTests_
    int numFailed() const
    { return countTests_ - countPasses_; }

    // allPassed
    // Returns true if all tests since last reset have passed
    // Pre: None.
    // Post:
    //     return == (countPasses_ == countTests_)
    bool allPassed() const
    { return countPasses_ == countTests_; }

    // setTolerance
    // Sets tolerance_ to given value
    // Pre: None.
    // Post:
    //     tolerance_ = abs(theTolerance)
    void setTolerance(double theTolerance)
    { tolerance_ = (theTolerance >= 0 ? theTolerance : -theTolerance); }

// ***** Tester: data members *****
private:

    int countTests_;    // Number of tests done since last reset
    int countPasses_;   // Number of tests passed since last reset
    double tolerance_;  // Tolerance for floating-point near-equality tests

};  // end class Tester


// ************************************************************************
// Class for Counting Ctor/Dctor Calls
// ************************************************************************


// class CallCounter
// Item type for counting ctor & dctor calls
// Increments static data member testItemCount
//  on default construction and destruction.
// Invariants:
//     CallCounter::callCount_ is number of calls to default
//      ctor and/or dctor for all CallCounter objects, since
//      most recent call to resetCount, or start of program
//      if resetCount has never been called.
class CallCounter {

// ***** CallCounter: Ctors, dctor, op= *****
public:

    // Default ctor
    // Pre: None.
    // Post:
    //     (testItemCount_ has been incremented.)
    CallCounter()
    { ++callCount_; }

    // Copy ctor
    // Pre: None.
    // Post:
    //     (testItemCount_ has been incremented.)
    CallCounter(const CallCounter & other)
    { ++callCount_; }

    // Copy assignment
    // Pre: None.
    // Post:
    //     Return value is *this.
    //     (testItemCount_ has been incremented.)
    CallCounter & operator=(const CallCounter & rhs)
    { ++callCount_; return *this; }

    // Dctor
    // Pre: None.
    // Post:
    //     (testItemCount_ has been incremented.)
    ~CallCounter()
    { ++callCount_; }

// ***** CallCounter: Functions dealing with count *****
public:

    // resetCount
    // Pre: None.
    // Post:
    //     testItemCount_ == 0.
    static void resetCount()
    { callCount_ = 0; }

    // getCount
    // Pre: None.
    // Post:
    //     return == testItemCount_.
    static int getCount()
    { return callCount_; }

// ***** CallCounter: Data Members *****
private:

    static int callCount_;  // Counts default ctor, dctor calls

};  // End class CallCounter

// Definition of static data member of class CallCounter
int CallCounter::callCount_ = 0;


// ************************************************************************
// Type Checking Class
// ************************************************************************


// class TypeCheck
// This class exists in order to have static member function check, which
// takes a parameter of a given type, by reference. Objects of type
// TypeCheck<T> cannot be created.
// Usage:
//     TypeCheck<MyType>::check(x)
//     returns true if the type of x is (MyType) or (const MyType),
//     otherwise false.
// Invariants: None.
// Requirements on Types: None.
template<typename T>
class TypeCheck {

private:

    // Uncopyable class. Do not define copy ctor, copy assn.
    TypeCheck(const TypeCheck &);
    TypeCheck<T> & operator=(const TypeCheck &);

    // Compiler-generated dctor is used (but irrelevant).

public:

    // check
    // These two functions simulate a single function that takes a
    // single parameter, and returns true iff the parameter has type
    // T or (const T).

    // check (reference-to-const to T)
    // Pre: None.
    // Post:
    //     Return is true.
    // Does not throw (No-Throw Guarantee)
    static bool check(const T & param)
    { return true; }

    // check (reference-to-const to non-T)
    // Pre: None.
    // Post:
    //     Return is false.
    // Does not throw (No-Throw Guarantee)
    template <typename OtherType>
    static bool check(const OtherType & param)
    { return false; }

};  // End class TypeCheck


// ************************************************************************
// Test Suite Functions
// ************************************************************************


// test_class_SSArray_types
// Test suite for class SSArray, types
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_types(Tester & t)
{
    std::cout << "Test Suite: class SSArray - types" << std::endl;

    bool correctType;  // result of type checking

    // value_type test #1: int
    SSArray<int>::value_type i1 = 0;
    correctType = TypeCheck<int>::check(i1);
    t.test(correctType, "value_type test #1");

    // value_type test #2: double
    SSArray<double>::value_type d1 = 0.;
    correctType = TypeCheck<double>::check(d1);
    t.test(correctType, "value_type test #2");

    // value_type check modifiability (only needs to compile)
    SSArray<double>::value_type d2;
    d2 = 0.;
    t.test(true, "value_type check modifiability");

    // size_type test
    SSArray<CallCounter>::size_type s1 = 0;
    correctType = TypeCheck<std::size_t>::check(s1)
               || TypeCheck<std::ptrdiff_t>::check(s1);
    t.test(correctType, "size_type test");

    // size_type check modifiability (only needs to compile)
    SSArray<CallCounter>::size_type s2;
    s2 = 0;
    t.test(true, "size_type check modifiability");
}


// test_class_SSArray_size_and_ctor_from_size
// Test suite for class SSArray, function size and ctor from size
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_size_and_ctor_from_size(Tester & t)
{
    std::cout << "Test Suite: class SSArray - function size, ctor from size" << std::endl;

    bool correctType;  // result of type checking

    const SSArray<int> ssai1(1);

    correctType = TypeCheck<SSArray<int>::size_type>::check(ssai1.size());
    t.test(correctType, "size, return type");

    t.test(ssai1.size() == 1, "size, ctor from size (const) #1");

    const SSArray<int> ssai2(10);
    t.test(ssai2.size() == 10, "size, ctor from size (const) #2)");

    const SSArray<double> ssad(100);
    t.test(ssad.size() == 100, "size, ctor from size (const) #3)");

    SSArray<int> ssai3(20);
    t.test(ssai3.size() == 20, "size, ctor from size (non-const)");
}


// test_class_SSArray_default_ctor
// Test suite for class SSArray, default ctor
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate have been messages printed to cout.
void test_class_SSArray_default_ctor(Tester & t)
{
    std::cout << "Test Suite: class SSArray - default ctor" << std::endl;

    const SSArray<int> ssai1;
    t.test(ssai1.size() == 10, "default ctor, size");
}


// test_class_SSArray_bracket_op
// Test suite for class SSArray, bracket operator
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_bracket_op(Tester & t)
{
    std::cout << "Test Suite: class SSArray, bracket operator" << std::endl;

    bool correctType;  // result of type checking

    const int theSize = 10;
    bool noErrors;  // True if no errors encountered
    int i;          // Counter

    SSArray<double> ssad1;
    correctType = TypeCheck<SSArray<double>::value_type>::check(ssad1[1]);
    t.test(correctType, "Bracket operator (non-const), return type");

    SSArray<int> ssai(theSize);
    for (i = 0; i < theSize; ++i)
        ssai[i] = 15 - i * i;

    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssai[i] != 15 - i * i)
            noErrors = false;
    }
    t.test(noErrors, "Bracket operator (non-const) #1");

    ssai[2] = 1000;
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssai[i] != ((i == 2) ? 1000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Bracket operator (non-const) #2");

    // Make const version, no copy
    const SSArray<int> & ssaiRef = ssai;

    const SSArray<double> ssad2;
    correctType = TypeCheck<SSArray<double>::value_type>::check(ssad2[1]);
    t.test(correctType, "Bracket operator (const), return type");

    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiRef[i] != ((i == 2) ? 1000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Bracket operator (const)");

}


// test_class_SSArray_two_param_ctor
// Test suite for class SSArray, 2-parameter ctor
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_two_param_ctor(Tester & t)
{
    std::cout << "Test Suite: class SSArray, 2-parameter ctor" << std::endl;

    const int theSize = 10;
    bool noErrors;                 // True if no errors encountered
    const double theValue = 5.34;  // Initial value for items in test array
    int i;                         // Counter

    const SSArray<double> ssad(theSize, theValue);

    t.test(ssad.size() == theSize, "2-param ctor - size");

    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssad[i] != theValue)
            noErrors = false;
    }
    t.test(noErrors, "2-param ctor - values");
}


// test_class_SSArray_copy_ctor
// Test suite for class SSArray, copy ctor
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_copy_ctor(Tester & t)
{
    std::cout << "Test Suite: class SSArray - copy ctor" << std::endl;

    const int theSize = 10;
    bool noErrors;  // True if no errors encountered
    int i;          // Counter

    SSArray<int> ssai(theSize);
    for (i = 0; i < theSize; ++i)
        ssai[i] = 15 - i * i;

    // Make const version, no copy
    const SSArray<int> & ssaiRef = ssai;
    // Make copy (copy ctor)
    SSArray<int> ssaiCopy(ssaiRef);

    t.test(ssaiCopy.size() == theSize, "Copy ctor - check size, copy");

    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiCopy[i] != 15 - i * i)
            noErrors = false;
    }
    t.test(noErrors, "Copy ctor - check values, copy");

    // Change original
    ssai[2] = 1000;

    // Check original
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssai[i] != ((i == 2) ? 1000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Copy ctor - change original, check values, original");

    // Check copy
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiCopy[i] != 15 - i * i)
            noErrors = false;
    }
    t.test(noErrors, "Copy ctor - change original, check values, copy");

    // Change copy
    ssaiCopy[3] = 2000;

    // Check original
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssai[i] != ((i == 2) ? 1000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Copy ctor - change copy, check values, original");

    // Check copy
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiCopy[i] != ((i == 3) ? 2000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Copy ctor - change copy, check values, copy");
}


// test_class_SSArray_copy_assn
// Test suite for class SSArray, copy assignment
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_copy_assn(Tester & t)
{
    std::cout << "Test Suite: class SSArray - copy assignment" << std::endl;

    const int theSize = 10;
    bool noErrors;  // True if no errors encountered
    int i;          // Counter

    SSArray<int> ssai(theSize);
    for (i = 0; i < theSize; ++i)
        ssai[i] = 15 - i * i;

    // Make const version, no copy
    const SSArray<int> & ssaiRef = ssai;
    // Make copy (copy ctor)
    SSArray<int> ssaiCopy(1);
    ssaiCopy = ssaiRef;

    t.test(ssaiCopy.size() == theSize, "Copy assn - check size, copy");

    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiCopy[i] != 15 - i * i)
            noErrors = false;
    }
    t.test(noErrors, "Copy assn - check values, copy");

    // Change original
    ssai[2] = 1000;

    // Check original
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssai[i] != ((i == 2) ? 1000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Copy assn - change original, check values, original");

    // Check copy
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiCopy[i] != 15 - i * i)
            noErrors = false;
    }
    t.test(noErrors, "Copy assn - change original, check values, copy");

    // Change copy
    ssaiCopy[3] = 2000;

    // Check original
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssai[i] != ((i == 2) ? 1000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Copy assn - change copy, check values, original");

    // Check copy
    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiCopy[i] != ((i == 3) ? 2000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Copy assn - change copy, check values, copy");

    // Check self-assignment
    ssaiCopy = ssaiCopy;

    noErrors = true;
    for (i = 0; i < theSize; ++i)
    {
        if (ssaiCopy[i] != ((i == 3) ? 2000 : 15 - i * i))
            noErrors = false;
    }
    t.test(noErrors, "Copy assn - values after self-assignment");
}


// test_class_SSArray_begin_end
// Test suite for class SSArray, functions begin & end
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_begin_end(Tester & t)
{
    std::cout << "Test Suite: class SSArray - functions begin & end" << std::endl;

    bool correctType;  // result of type checking

    const int theSize = 10;
    bool noErrors;      // True if no errors encountered
    int i;              // Counter
    int * iter;         // iterator
    const int * citer;  // const_iterator

    SSArray<int> ssai(theSize);
    for (iter = ssai.begin(), i = 0; iter != ssai.end(); ++iter, ++i)
        *iter = 15 - i * i;

    // Non-const test
    SSArray<double> ssad1;

    correctType = TypeCheck<SSArray<double>::value_type *>::check(ssad1.begin());
    t.test(correctType, "begin (non-const), return type");
    
    correctType = TypeCheck<SSArray<double>::value_type *>::check(ssad1.end());
    t.test(correctType, "end (non-const), return type");

    t.test(ssai.begin() != ssai.end(), "begin/end - inequality (non-const)");
    t.test (ssai.end() - ssai.begin() == theSize, "begin/end - check difference (non-const)");
    noErrors = true;
    for (iter = ssai.begin(), i = 0; iter != ssai.end(); ++iter, ++i)
    {
        if (*iter != 15 - i * i)
            noErrors = false;
    }
    t.test(noErrors, "begin/end - check values (non-const)");

    // Make const version, no copy
    const SSArray<int> & ssaiRef = ssai;

    // Const test
    const SSArray<double> ssad2;

    correctType = TypeCheck<const SSArray<double>::value_type *>::check(ssad2.begin());
    t.test(correctType, "begin (const), return type");
    
    correctType = TypeCheck<const SSArray<double>::value_type *>::check(ssad2.end());
    t.test(correctType, "end (const), return type");
    
    t.test(ssaiRef.end() - ssaiRef.begin() == theSize, "begin/end - check difference (const)");
    noErrors = true;
    for (citer = ssaiRef.begin(), i = 0; citer != ssaiRef.end(); ++citer, ++i)
    {
        if (*citer != 15 - i * i)
            noErrors = false;
    }
    t.test(noErrors, "begin/end - check values (const)");
}


// test_class_SSArray_comparisons
// Test suite for class SSArray, comparisons
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_comparisons(Tester & t)
{
    std::cout << "Test Suite: class SSArray - comparisons" << std::endl;

    bool correctType;  // result of type checking

    const int theSize = 10;
    int i;          // Counter

    SSArray<int> ssai1(theSize);
    for (i = 0; i < theSize; ++i)
        ssai1[i] = 15 - i * i;
    const SSArray<int> & ssai1Ref = ssai1;
    SSArray<int> ssai1Copy(ssai1Ref);
    SSArray<int> ssai2(theSize-1);
    for (i = 0; i < theSize-1; ++i)
        ssai2[i] = 15 - i * i;
    const SSArray<int> & ssai2Ref = ssai2;
    
    // operator== return type
    correctType = TypeCheck<bool>::check(ssai1 == ssai1Copy);
    t.test(correctType, "operator==, return type");

    // operator!= return type
    correctType = TypeCheck<bool>::check(ssai1 != ssai1Copy);
    t.test(correctType, "operator!=, return type");

    // Check equality of copies
    t.test(ssai1 == ssai1Copy, "Equality of copies");

    // Check inequality of copies
    t.test(!(ssai1 != ssai1Copy), "Inequality of copies");

    // Check equality of different sizes #1 (compilation checks constness of op==)
    t.test(!(ssai1Ref == ssai2Ref), "Equality of different sizes #1");

    // Check inequality of different sizes #1 (compilation checks constness of op!=)
    t.test(ssai1Ref != ssai2Ref, "Inequality of different sizes #1");

    // Check equality of different sizes #2
    t.test(!(ssai2Ref == ssai1Ref), "Equality of different sizes #2");

    // Check inequality of different sizes #2
    t.test(ssai2Ref != ssai1Ref, "Inequality of different sizes #2");

    // Modify copy
    ++ssai1Copy[theSize-1];

    // Check equality of modification of copy
    t.test(!(ssai1 == ssai1Copy), "Equality of modification of copy");

    // Check inequality of modification of copy
    t.test(ssai1 != ssai1Copy, "Inequality of modification of copy");
}


// test_class_SSArray_ctor_dctor_count
// Test suite for class SSArray, number of class to item type
//  ctor, dctor.
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray_ctor_dctor_count(Tester & t)
{
    std::cout << "Test Suite: class SSArray - ctor, dctor count" << std::endl;

    // Check number of value type ctor/dctor calls on array creation & destruction
    CallCounter::resetCount();
    { // Block, so we get dctor calls before function ends
        const SSArray<CallCounter> ssacc(10);

        t.test(CallCounter::getCount() == 10, "Counting default ctor calls due to array creation");

        CallCounter::resetCount();
    }
    t.test(CallCounter::getCount() == 10, "Counting dctor calls due to destruction");

    // Check correct number of value type ctor & dctor calls on self-assignment
    SSArray<CallCounter> ssacc2(10);
    CallCounter::resetCount();
    ssacc2 = ssacc2;
    int i1 = CallCounter::getCount();
    t.test(i1 == 0 || i1 == 20, "Self-assignment ctor/dctor calls");
}


// test_class_SSArray
// Test suite for class SSArray
// Uses other test-suite functions
// Pre: None.
// Post:
//     Pass/fail status of tests have been registered with t.
//     Appropriate messages have been printed to cout.
void test_class_SSArray(Tester & t)
{
    // Do all the test suites
    std::cout << "TEST SUITES FOR CLASS SSArray" << std::endl;
    test_class_SSArray_types(t);
    test_class_SSArray_size_and_ctor_from_size(t);
    test_class_SSArray_default_ctor(t);
    test_class_SSArray_bracket_op(t);
    test_class_SSArray_two_param_ctor(t);
    test_class_SSArray_copy_ctor(t);
    test_class_SSArray_copy_assn(t);
    test_class_SSArray_begin_end(t);
    test_class_SSArray_comparisons(t);
    test_class_SSArray_ctor_dctor_count(t);
}


// ************************************************************************
// Main program
// ************************************************************************


// main
// Runs class SSArray test suite, prints results to cout.
int main()
{
    Tester t;
    test_class_SSArray(t);

    std::cout << std::endl;
    if (t.allPassed())
    {
        std::cout << "All tests successful" 
                  << std::endl;
    }
    else
    {
        std::cout << "Tests ********** UNSUCCESSFUL **********"
                  << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

  #2  
Old 25-Sep-2007, 05:37
davis
 
Posts: n/a

Re: Smart Array problem...


Here's what I got as a result of attempting to compile this load:

Code:
ssarray.h: In copy constructor 'SSArray<T>::SSArray(const SSArray<T>&)': ssarray.h:53: error: expected primary-expression before ']' token ssarray_test.cpp: At global scope: ssarray_test.cpp:184: warning: unused parameter 'other' ssarray_test.cpp:192: warning: unused parameter 'rhs' ssarray_test.cpp: In function 'void test_class_SSArray_bracket_op(Tester&)': ssarray_test.cpp:395: error: invalid lvalue in assignment ssarray_test.cpp:405: error: invalid lvalue in assignment ssarray_test.cpp: In function 'void test_class_SSArray_two_param_ctor(Tester&)': ssarray_test.cpp:449: warning: comparison between signed and unsigned integer expressions ssarray_test.cpp: In function 'void test_class_SSArray_copy_ctor(Tester&)': ssarray_test.cpp:477: error: invalid lvalue in assignment ssarray_test.cpp:484: warning: comparison between signed and unsigned integer expressions ssarray_test.cpp:495: error: invalid lvalue in assignment ssarray_test.cpp:516: error: invalid lvalue in assignment ssarray_test.cpp: In function 'void test_class_SSArray_copy_assn(Tester&)': ssarray_test.cpp:554: error: invalid lvalue in assignment ssarray_test.cpp:562: warning: comparison between signed and unsigned integer expressions ssarray_test.cpp:573: error: invalid lvalue in assignment ssarray_test.cpp:594: error: invalid lvalue in assignment ssarray_test.cpp: In function 'void test_class_SSArray_comparisons(Tester&)': ssarray_test.cpp:708: error: invalid lvalue in assignment ssarray_test.cpp:713: error: invalid lvalue in assignment ssarray_test.cpp:743: error: invalid lvalue in increment ssarray_test.cpp: At global scope: ssarray_test.cpp: In instantiation of 'static bool TypeCheck<T>::check(const T&) [with T = int]': ssarray_test.cpp:302: instantiated from here ssarray_test.cpp:268: warning: unused parameter 'param' ssarray_test.cpp: In instantiation of 'static bool TypeCheck<T>::check(const T&) [with T = double]': ssarray_test.cpp:307: instantiated from here ssarray_test.cpp:268: warning: unused parameter 'param' ssarray_test.cpp: In instantiation of 'static bool TypeCheck<T>::check(const T&) [with T = unsigned int]': ssarray_test.cpp:317: instantiated from here ssarray_test.cpp:268: warning: unused parameter 'param' ssarray_test.cpp: In instantiation of 'static bool TypeCheck<T>::check(const OtherType&) [with OtherType = size_t, T = int]': ssarray_test.cpp:318: instantiated from here ssarray_test.cpp:277: warning: unused parameter 'param' ssarray.h: In member function 'size_t& SSArray<T>::size() const [with T = int]': ssarray_test.cpp:342: instantiated from here ssarray.h:114: error: invalid initialization of reference of type 'size_t&' from expression of type 'const size_t' ssarray.h: In member function 'size_t& SSArray<T>::size() const [with T = double]': ssarray_test.cpp:351: instantiated from here ssarray.h:114: error: invalid initialization of reference of type 'size_t&' from expression of type 'const size_t' ssarray.h: In constructor 'SSArray<T>::SSArray(size_t, const T&) [with T = double]': ssarray_test.cpp:447: instantiated from here ssarray.h:37: error: invalid use of member (did you forget the '&' ?) ssarray.h: In copy constructor 'SSArray<T>::SSArray(const SSArray<T>&) [with T = int]': ssarray_test.cpp:482: instantiated from here ssarray.h:51: error: invalid use of member (did you forget the '&' ?) ssarray.h:53: error: array subscript is not an integer ssarray.h: In member function 'SSArray<T>& SSArray<T>::operator=(const SSArray<T>&) [with T = int]': ssarray_test.cpp:560: instantiated from here ssarray.h:70: error: no match for 'operator!=' in 'this != otherArray' ssarray.h: In member function 'T* SSArray<T>::begin() const [with T = int]': ssarray_test.cpp:646: instantiated from here ssarray.h:119: error: invalid conversion from 'const int*' to 'int*' ssarray.h: In member function 'T* SSArray<T>::end() const [with T = int]': ssarray_test.cpp:646: instantiated from here ssarray.h:124: error: array subscript is not an integer ssarray.h: In member function 'T* SSArray<T>::begin() const [with T = double]': ssarray_test.cpp:652: instantiated from here ssarray.h:119: error: invalid conversion from 'const double*' to 'double*' ssarray_test.cpp: At global scope: ssarray_test.cpp: In instantiation of 'static bool TypeCheck<T>::check(const T&) [with T = double*]': ssarray_test.cpp:652: instantiated from here ssarray_test.cpp:268: warning: unused parameter 'param' ssarray.h: In member function 'T* SSArray<T>::end() const [with T = double]': ssarray_test.cpp:655: instantiated from here ssarray.h:124: error: array subscript is not an integer ssarray_test.cpp: At global scope: ssarray_test.cpp: In instantiation of 'static bool TypeCheck<T>::check(const OtherType&) [with OtherType = double*, T = const double*]': ssarray_test.cpp:674: instantiated from here ssarray_test.cpp:277: warning: unused parameter 'param' ssarray.h: In member function 'bool& SSArray<T>::operator==(const SSArray<T>&) const [with T = int]': ssarray_test.cpp:717: instantiated from here ssarray.h:91: warning: comparison between signed and unsigned integer expressions ssarray.h:90: warning: reference to local variable 'equ' returned ssarray_test.cpp: At global scope: ssarray_test.cpp: In instantiation of 'static bool TypeCheck<T>::check(const T&) [with T = bool]': ssarray_test.cpp:717: instantiated from here ssarray_test.cpp:268: warning: unused parameter 'param' ssarray.h: In member function 'bool& SSArray<T>::operator!=(const SSArray<T>&) const [with T = int]': ssarray_test.cpp:721: instantiated from here ssarray.h:107: error: invalid initialization of non-const reference of type 'bool&' from a temporary of type 'bool' ssarray.h: In member function 'SSArray<T>& SSArray<T>::operator=(const SSArray<T>&) [with T = CallCounter]': ssarray_test.cpp:778: instantiated from here ssarray.h:70: error: no match for 'operator!=' in 'this != otherArray' ssarray.h: In member function 'T* SSArray<T>::begin() const [with T = CallCounter]': ssarray.h:72: instantiated from 'SSArray<T>& SSArray<T>::operator=(const SSArray<T>&) [with T = CallCounter]' ssarray_test.cpp:778: instantiated from here ssarray.h:119: error: invalid conversion from 'const CallCounter*' to 'CallCounter*' ssarray.h: In member function 'T* SSArray<T>::end() const [with T = CallCounter]': ssarray.h:72: instantiated from 'SSArray<T>& SSArray<T>::operator=(const SSArray<T>&) [with T = CallCounter]' ssarray_test.cpp:778: instantiated from here ssarray.h:124: error: array subscript is not an integer ssarray.h: In member function 'size_t& SSArray<T>::size() const [with T = CallCounter]': ssarray.h:124: instantiated from 'T* SSArray<T>::end() const [with T = CallCounter]' ssarray.h:72: instantiated from 'SSArray<T>& SSArray<T>::operator=(const SSArray<T>&) [with T = CallCounter]' ssarray_test.cpp:778: instantiated from here ssarray.h:114: error: invalid initialization of reference of type 'size_t&' from expression of type 'const size_t'

"ssarray_test.cpp" 835L, 24449C


There are a lot of errors that stem from code you haven't yet written.

Why is your data public?

Instead of summarizing error messages, you may want to include the complete content of the output produced by your compiler.

Look at this:

CPP / C++ / C Code:
    size_type & size() const
    {
        return size_;
    }

    value_type* end() const
    {
        return &arr[size];
    }

public:  // public?!
    //variables
    size_type size_;

This is one of the challenges that you'll face in variable naming. You have an operation named "size" and then you try to use arr[size] instead of arr[size_].

This is at least one of the reasons why you'll often find m_ prefixed on member variables.

It looks like you've got your work cut out for yourself.


:davis:
  #3  
Old 25-Sep-2007, 18:16
crazy_ivan crazy_ivan is offline
New Member
 
Join Date: Sep 2007
Posts: 7
crazy_ivan is on a distinguished road

Re: Smart Array problem...


Ok, here is an updated version of the code that I have done today. I think I might have fixed most of the const/non-const conversion errors...but I have no way to check because all the compiler (visual studio) gives me is 11 errors, all of the same type (error C2106: '=' : left operand must be l-value). I still have no idea why it does that...another question, davis, what compiler did you use to get those errors and have it skip over the "error C2106: '=' : left operand must be l-value" error?

here is updated version of code:
CPP / C++ / C Code:
//ssarray.h
//Ilia Pinchuk
//25 September 2007


#ifndef FILE_SSARRAY_H_INCLUDED // ifndef inclusion
#define FILE_SSARRAY_H_INCLUDED

// #include's
#include <cstdlib>  // for std::size_t
#include <algorithm> // for std::swap

template <typename T>

class SSArray
{

public:

	//typedef's
	typedef std::size_t size_type;
	typedef T value_type;  
	

	//default ctor
	//creates new object
	//pre: none
	//post: SSArray of size 10 is created.
	SSArray()
		:length(10)
	{}

	//1-param ctor
	//creates new object with size of param
	//pre: none
	//post: SSArray of size sizeIn is created.
	SSArray(size_type sizeIn)
		:length(sizeIn)
	{}

	//2-param ctor
	//creates new object with size of param and value val.
	//pre: none
	//post: SSArray of size sizeIn is created and all values in array are valIn.
	SSArray(size_type sizeIn, const value_type & valIn)
		:length(sizeIn),val(valIn))
	{
		for(int i=0; i<=size; i++)
		{
			//set all array values to val for size.
			arr[i] = val;
		}
	}


	//copy ctor
	//copies values of arr into arbitrary otherArray
	//Pre: arr and otherArray exsist; size >=0
	//Post: arr contains values of otherArray
	SSArray(const SSArray & otherArray)
	{
		for(int i=0; i<=otherArray.length; ++i)
		{
			std::copy(otherArray.begin(), otherArray.end(), arr);
		}
	}

	//dcor
	//destroys object
	//pre:none
	//post:object is destroyed.
	~SSArray()
	{
		delete [] iter;
	}

//***overloaded operators***
public:

	//copy assignment
	//copies otherArray into *this array
	//pre: otherArray and arr exsist
	//post: arr contains values of otherArray
	SSArray & operator=(const SSArray & otherArray)
	{
		for(int i=0; i<otherArray.size(); ++i)
		{
			arr[i] = otherArray[i];
			//std::copy(otherArray.begin(), otherArray.end(), arr[]);
		}
		return *this;
	}

	//const and non-const [] operator
	//takes index and returns value at index
	//pre: index is between 0 and length-1
	//post: none
	value_type operator[](int index)
	{
		return arr[index];
	}
	
	value_type operator[](int index) const
	{
		return arr[index];
	}
	
	//operator== 
	//compares equality of arr and otherArray
	//pre: both arrays exsist and size is not negetive
	//post: returns if array is equal.
	bool  operator==(const SSArray & otherArray) const
	{
		for(int i=0; i<otherArray.length(); ++i)
		{
			if(arr[i] != otherArray[i])
			{
				return false;
				break;
			}
		}
	}

	
	//operator!= 
	//compares non-equality of arr and otherArray
	//pre: both arrays exsist and size is not negetive
	//post: returns if array is non-equal.
	bool  operator !=(const SSArray & otherArray) const
	{
		for(int i=0; i<otherArray.size(); ++i)
		{
			if(arr[i] == otherArray[i])
			{
				return false;
				break;
			}
		}
	}

public:

	//size fnc
	//return size of array
	//pre: none
	//post: none
	size_type  size() const
	{
		return length;
	}

	//begin fnc
	//return pointer to start of array
	//pre: arr exsists
	//post: returns pointer to address of begining array
	value_type* begin() const
	{
		return &arr[0];
	}

	//end fnc
	//return pointer to end of array
	//pre: arr exsists
	//post: returns pointer to address of end array
	value_type* end() const
	{
		return &arr[length];
	}







private:
	//variables
	size_type length;
	value_type val;
	value_type arr[10];
	value_type* iter;

}; //end class ssarray

#endif //end file inclusion

and the output from the compiler is this:
------ Build started: Project: ssaray, Configuration: Debug Win32 ------
Compiling...
ssarray_test.cpp
.\ssarray_test.cpp(401) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(411) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(483) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(501) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(522) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(560) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(579) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(600) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(714) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(719) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(749) : error C2105: '++' needs l-value
11 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
  #4  
Old 25-Sep-2007, 19:30
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,006
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Smart Array problem...


So... you gave the updated header file, what about the cpp file? I get a several more errors using this new header file with the cpp file in the first post.

Davis probably used gcc (or g++), but either way, he didn't 'skip' over any errors. Note in his list of errors, the ones labeled: "error: invalid lvalue in assignment", are the same as yours, but just from a different compiler.

Unless I'm missing the purpose of the SSArray class, it appears that some arrays are declared using ( ) instead of [ ]. Changing some of those clears the error, but note that in other places, where you assign one array to another, might also need tweaking after the change(s).
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #5  
Old 26-Sep-2007, 17:06
crazy_ivan crazy_ivan is offline
New Member
 
Join Date: Sep 2007
Posts: 7
crazy_ivan is on a distinguished road

Re: Smart Array problem


Well, the this is we are not supposed to change the test program (.cpp file), but make our header file work with the ssarray_test file. When you say that some of the arrays are declared () instead of [], exactly where do you mean? I looked through my code and, unless I missed a concept, couldn't find any places that declare the array with anything other than[]. (although I admit I am rather rusty with C++... )
  #6  
Old 27-Sep-2007, 02:01
Kimmo Kimmo is offline
Member
 
Join Date: Mar 2007
Location: Finland
Posts: 229
Kimmo has a spectacular aura aboutKimmo has a spectacular aura about

Re: Smart Array problem...


Quote:
Originally Posted by crazy_ivan
------ Build started: Project: ssaray, Configuration: Debug Win32 ------
Compiling...
ssarray_test.cpp
.\ssarray_test.cpp(401) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(411) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(483) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(501) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(522) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(560) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(579) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(600) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(714) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(719) : error C2106: '=' : left operand must be l-value
.\ssarray_test.cpp(749) : error C2105: '++' needs l-value
11 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
If I got it right, it's because your operator[]() return the valueType by value. That is, it's effectively the same as doing something like
CPP / C++ / C Code:
5 = 5 + 5;
There's no variable to assign the right-hand side to.

Changing the return type to a reference should get you somewhere. Don't know if that's the best solution.
__________________
Music, programming, endless learning..
 
 

Recent GIDBlogPython ebook by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Need help deleting the last element in the array headphone69 C++ Forum 2 15-Mar-2006 20:31
array problem vaha C Programming Language 9 18-May-2005 13:23
problem modifying an array of char in a function ronin C Programming Language 10 28-Mar-2005 19:15
template comiling problems - need expert debugger! crq C++ Forum 1 01-Feb-2005 22:26
Problem in array Kay Chan C Programming Language 2 05-Oct-2004 22:16

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 08:32.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.