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 28-Jan-2005, 11:55
crq crq is offline
New Member
 
Join Date: Jan 2005
Posts: 15
crq is on a distinguished road

template comiling problems - need expert debugger!


hi there. i am on a UNIX system and am writing a template code called Array.h. it is called by a Test2.C file which does nothing more than declare a T object of type int. Array<int>.

i am getting all kinds of compile errors. have been over it and over it for about 8 hours now. can anyone help me here. i know there is something wrong with my non-member functions and i know there is something wrong with my init method that constructs my T's.

this is what i am getting from the compiler when i run Test2.C

Array.h:71: syntax error before `&' token
Array.h:71: `ostream' was not declared in this scope
Array.h:71: `os' was not declared in this scope
Array.h:71: syntax error before `<' token
Array.h:71: ISO C++ forbids declaration of `operator<<' with no type
Array.h:71: `int& operator<<(...)' must have an argument of class or enumerated
type
Array.h:71: `int& operator<<(...)' must take exactly two arguments
Array.h: In member function `void Array<T>::init(const T*, int)':
Array.h:349: syntax error before `;' token
Array.h: At global scope:
Array.h:366: syntax error before `>' token
Array.h:370: `b' was not declared in this scope
Array.h:370: syntax error before `;' token
Array.h:370: syntax error before `++' token

if anyone wanted to help me figure out what is going on with this mess that would be great. this is only PART A of what i need to be doing (ha ha).

and this is my Array.h of template T
CPP / C++ / C Code:

#include <assert.h>
#include <iostream>                           // system files
                                              
#include "/unc/hedlund/121/lib/cpluslib.h"    // comp 121 library

                                              // GLOBAL CONSTANTS
const int NOT_FOUND = -1;                     // returned when para not in array
                                              
template<class T>
class Array
{                                                  
                                              
protected:
        static const int DEF_SIZE = 100;      // default array size
  
                                              
public:                                       // CONSTRUCTORS
                                              // default constructor
                                              // size = # of array elements
                                              // all elements initialized to 0
        Array ( int sz = DEF_SIZE );
                                              
                                              // copy constructor
                                              // new array is a deep copy of x
        Array ( const Array<T>& x );
                                              
        virtual ~Array();                     // destructor
        

                                              // OBSERVER FUNCTIONS
        int size() const;                     // return # of array elements  
        
                                              // equality-identical in size and
                                              // contents of each array element?
        bool operator == ( const Array<T> &rhs ) const;

                                              // inequality
        bool operator != ( const Array<T> &rhs ) const;
                                              
        bool invariant () const;              // is the object in a consistent state?
  
                                              // MUTABLE FUNCTIONS
                                              // assignment-contents of RHS are copied
                                              // to LHS (self)
        Array<T>& operator = ( const Array<T> &rhs );
  
                                              // index into array.  No bounds checking.
        T& operator [] ( int i ) const;
        
 
protected:
                                              // INTERNAL DATA REPRESENTATION
        int d_num_elements;                   // # of data elements

        T* d_array;  // ptr to first element of array
      
   
private:
                                              // PRIVATE MEMBER FUNCTIONS
                                                   [ Wrote 396 lines ]

classroom(52)% more Array.h

#include <assert.h>
#include <iostream>                           // system files
        
#include "/unc/hedlund/121/lib/cpluslib.h"    // comp 121 library

                                              // GLOBAL CONSTANTS
const int NOT_FOUND = -1;                     // returned when para not in array

template<class T>
class Array
{

protected:
        static const int DEF_SIZE = 100;      // default array size


public:                                       // CONSTRUCTORS
                                              // default constructor
                                              // size = # of array elements
                                              // all elements initialized to 0
        Array ( int sz = DEF_SIZE );

                                              // copy constructor
                                              // new array is a deep copy of x
        Array ( const Array<T>& x );
                                              
        virtual ~Array();                     // destructor


                                              // OBSERVER FUNCTIONS
        int size() const;                     // return # of array elements

                                              // equality-identical in size and
                                              // contents of each array element?
        bool operator == ( const Array<T> &rhs ) const;                  

                                              // inequality
        bool operator != ( const Array<T> &rhs ) const; 
                                               
        bool invariant () const;              // is the object in a consistent state?

                                              // MUTABLE FUNCTIONS
                                              // assignment-contents of RHS are copied
                                              // to LHS (self)
        Array<T>& operator = ( const Array<T> &rhs );

                                              // index into array.  No bounds checking.
        T& operator [] ( int i ) const;


protected:
                                              // INTERNAL DATA REPRESENTATION
        int d_num_elements;                   // # of data elements
        
        T* d_array;  // ptr to first element of array
       

private:
                                              // PRIVATE MEMBER FUNCTIONS
                                              // array initialization
        void init ( const T *x, int sz );
};


// 
// -------------------------NON-MEMBER FUNCTION PROTOTYPES-----------------------
//

        template<class T>                       // << displays array elements one per line
        ostream& operator << ( ostream& os, const Array<T> & b );

                                             // return first position of v in
        template<class T>                    // array b or NOT_FOUND if v not in array
        int includes ( const Array<T> &b, int v);


//
//
// ---------------------------------CONSTRUCTORS---------------------------------
//

//
// default constructor - initialize all elements to 0
// Parameters
//    INBOUND - sz = # of elements in array
// Pre - sufficient free memeory available AND ( 0 <= sz <= MAXINT)
// Post - creates a new array of sz elements AND sz == size() 
// Runtime - 0(n)
//
template<class T> 
Array<T>::
Array ( int sz )
{
                                                   // pre-condition assertion
        assert ( 0 <= sz <= MAXINT );              
        cout << "!!! IntArray default constructor called" <<endl;

                                                   // init() called to initialize d_array
                                                   // to 0 and d_num_elements to
                                                   // to DEF_SIZE or sz
        init ( T(), sz );
}


//
// copy constructor - make a deep copy of x
// Parameters
//    INBOUND - x = array to copy
// Pre - sufficient free memeory available
// Post - creates a new array of x.size() elements AND
//      AND self == x  AND old_self is deleted
// Runtime - 0(n)
// 
template<class T>
Array<T>::
Array ( const Array<T>& x )
{
        cout << "!!! IntArray copy constructor called" <<endl;
                                                   
                                                   // init() called to initialize d_array
                                                   // to x.d_array and d_num_elements
                                                   // to x.size()
        init ( x.d_array, x.size() );
}


//
// destructor - releases memory used
// Pre - TRUE
// Post - reclaim memory used for
// Runtime - 0(1)
// 
template<class T>
Array<T>::
~Array()
{                                               
                                                   // delete entire array d_array
        cout << "!!! IntArray destructor called" <<endl;
        if ( size() > 0 ) {
                delete [] d_array;
        }
}


//
//------------------------------OBSERVER FUNCTIONS-----------------------------
//


//
// size - returns the # of elements in an array
// Parameters
//    OUTBOUND - d_num_elements = number of elements in array
// Pre - TRUE
// Post - d_num_elements == size()
// Runtime - 0(1)
//
template<class T>
int Array<T>::
size () const
{
                                              // size of d_array is d_num_elements
        return (d_num_elements);

}  


//
// equality - are the 2 arrays identical?  They must match in size and
//          contents of each array element
// Parameters
//    INBOUND - rhs = RHS of equality
//    OUTBOUND - boolean true or false
// Pre - TRUE
// Post - if lhs == rhs return TRUE, else return FALSE
// Runtime - 0(n) worst case
// 
template<class T>
bool Array<T>::
operator == ( const Array<T> &rhs ) const
{
        if ( size() != rhs.size() ) {              // check for same # elements in      
                return ( FALSE );                  // lhs array and rhs array
        }
                                                   // if number of elements are equal
                                                   // check for the element contents of 
                                                   // lhs and rhs for equality
        int i = 0;     
cout<< "checking for equality" <<endl;                            
        while ( i < size() ){
                        // For all j: 0 .. i-1, self[j] == b[j]
                if ( self[i] != rhs[i] ){         
                        return ( FALSE );
                }
                else i++;
        }
        return ( TRUE );
}


//
// inequality - are the 2 arrays different?  They can differ in size
//     or contents of any array element
// Parameters
//    INBOUND - rhs = RHS of inequality
//    OUTBOUND - boolean true or false
// Pre - TRUE
// Post - if lhs != ths then return TRUE, else return FALSE
// Runtime - 0(n) worst case
//
template<class T>
bool Array<T>::
operator != ( const Array<T> &rhs) const
{
        if ( size() == rhs.size() ) {               // check for same # elements 
                return ( FALSE );                   // in lhs array and rhs array
        }
                                                    // if number of elements are not
                                                    // equal check the elements of 
                                                    // lhs and rhs for inequality

        int i = 0;
cout<< "checking for inequality" <<endl;
        while ( i < size() ){
                        // For all j: 0 .. i-1, self[j] != b[j]
                if ( self[i] == rhs[i] ){
                        return ( TRUE );
                } 
                else i++;
        }               
        return ( FALSE );
}


//
// invariant - is the object in a consistent state?
// Parameters - OUTBOUND - bool TRUE or FALSE
// Pre - TRUE
// Post - return TRUE if object is consistent, else return FALSE
// Runtime - 0(1)
//
template<class T>
bool Array<T>::  
invariant() const
{
        bool inv1 = (TRUE);                         // d_array doesn't point to NULL
        if ( d_array == NULL){                      // i.e. d_array has been initialized
                inv1 = (FALSE);
        }

        bool inv2 = (TRUE);                         // d_array is equal to itself
        if ( d_array != d_array ){
                inv2 = (FALSE);
        }

        bool inv3 = (TRUE);                         // d_num_elements is equal to 
        if ( d_num_elements != size() ){            // size()
                inv3 = (FALSE);
        }
                                                    // return true if all conditions 
                                                    // are true, else return false
        return ( inv1 && inv2 && inv3);      
}                                                  


//
//------------------------------MUTABLE FUNCTIONS----------------------------
//


// 
// assignment - make a deep copy of rhs into lhs
// Parameters 
//    INBOUND - rhs = RHS of assignment
//    OUTBOUND - new LHS object (deep copy of RHS)
// Pre - TRUE
// Post - self == rhs AND old_self is deleted
// Runtime - 0(n)
//
template<class T>
Array<T> & Array<T>::
operator = ( const Array<T> &rhs )
{
        if ( this == &rhs ){                      // check for assignment to itself
                return ( self );
        }
                                                  // free existing memory of lhs
        if (size() > 0 ){
                delete [] d_array;
        }
        init ( rhs.d_array, rhs.size() );         // initialize copy of rhs
        assert ( invariant() );                   // check that new object is valid
        return ( self );
}


//
// indexing - index into array.  No bounds checking
// Parameters -
//     INBOUND - int i = index #
//     OUTBOUND - object of type T 
// Pre - TRUE   (since no bounds checking)
// Post - object of type T in index i returned
// Runtime - 0(n)
//
template<class T>
T & Array<T>::                                                       
operator [] ( int i ) const                                                        
{
        if ( d_array == NULL ){
                return( NOT_FOUND );
        }
        else{                                                                            
                return d_array[i];
        }
}                           
  

//
//--------------------------PRIVATE MEMBER FUNCTIONS----------------------------
//                                    


// init - create and initialize a new array.  If an array is passed as the first 
// parameter          


                                              
template<class T>
void Array<T>::
init ( const T *data, int sz )
{

        assert ( (0 <= sz) && (sz <= MAXINT));

        d_num_elements = sz;
        if ( 0 == d_num_elements ){
                d_array = NULL;
        }
        else{
                d_array = new T [d_num_elements];

                assert ( NULL != d_array );
        }

        for (int i = 0; i < sz; i++ ){
                if ( NULL == data[i] ){
                        self [i] = T;
                }
                else{
                        self[i] = data[i];
                }
        }
        assert ( invariant() );
}

                      
//
//-----------------------------NON- MEMBER FUNCTIONS----------------------------
//


// << - display array elements one per line

template<classT>
ostream &
operator << ( ostream & os, const Array<T> & b )
{
        for ( int i = 0; i < b.size(); i++ ){

                os << b[i] << endl;
        }
        return ( os );
} 


// includes - returns position of first v in b

template<class T>
int 
includes ( const Array<T>& b, int v)
{
        int i = 0;

        while ( i <b.size() ){
                if ( b[i] == v ){
                        return i;
                }
                else{
                        i++
                }
        }
        return (NOT_FOUND);
}
and this is my Test2.C
CPP / C++ / C Code:
int
main()
{

      


        cout<< "*******Declaration of 3 IntArray objects/size() checking******* \n" <<endl;

        cout<< "IntArray a declared with no parameters" <<endl;

        Array<int> a;
        cout << "   " <<endl;

return 0;
}

Last edited by LuciWiz : 29-Jan-2005 at 16:29. Reason: Please insert your C code between [c] & [/c] tags
  #2  
Old 01-Feb-2005, 21:26
QED's Avatar
QED QED is offline
Member
 
Join Date: Feb 2005
Location: Hudson Valley, NY
Posts: 231
QED is a jewel in the roughQED is a jewel in the roughQED is a jewel in the rough
I will try to point you in the right direction... Be warned that I am bored, so I hope you are really interested in learning here.

Your first 7 compile-time errors occur at line 71. Lets consider each.
Quote:
Array.h:71: syntax error before `&' token

In this case, this message indicates that the compiler did not recognize a symbol in line 71 that precedes an occurrence of the '&' operator. That operator occurs twice in the line, and both times is immediately preceded by the symbol 'ostream'. But before we draw a conclusion, let's look at the next message.
Quote:
Array.h:71: `ostream' was not declared in this scope
This message confirms our suspicion that the compiler did not recognize the symbol 'ostream'. Why not? Because all Standard C++ objects are defined within a namespace, called 'std'. If you have ever worked with Java, you might think of a namespace as the C++ analog to a Java package. The point here is that all symbols/classes defined in the 'std' namespace are meaningless outside of it, unless you explicitly include the namespace in the current context. Employ either a using-declaration (at the beginning of the file)

CPP / C++ / C Code:
using namespace std;
or the scope-resolution operator (where needed)

CPP / C++ / C Code:
std::ostream
I recommend the former for implementation (.cpp) files, and the latter for headers (.h). This way you don't have to type 'std::' all the time in funciton definitions, but you also don't force the use of the namespace inadvertently in any file that includes your header.

Now, if the compiler did not understand the typename 'ostream', you can guess what the next message means.
Quote:
Array.h:71: `os' was not declared in this scope
In fact, think about all the remaining error messages for line 71. See if you can figure out how this one problem with the 'ostream' causes each those errors.

Next, on line 349, pay close attention to the right side of the assignment statement. What is wrong with this picture (remember, T is a typename)?

CPP / C++ / C Code:
self [i] = T;

On line 366, again look carefully at what you've typed.

CPP / C++ / C Code:
template<classT>
Fixing the problem here should also resolve the errors on line 370. Can you see why?

After identifying and fixing these errors in your code, see if you can continue to work through other problems. Remember, the messages the compiler spits out usually have more than enough information to guide you, if you learn how to read them.

Good luck. :-)
 
 

Recent GIDBlogToyota - 2008 September Promotion by Nihal

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
Error C2146: syntax error : missing ',' before identifier 'C4' mattchew008 C++ Forum 2 19-Dec-2004 06:06

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

All times are GMT -6. The time now is 04:55.


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