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 14-Jul-2009, 20:15
nanchuangyeyu nanchuangyeyu is offline
New Member
 
Join Date: Apr 2009
Posts: 15
nanchuangyeyu has a little shameless behaviour in the past

Error C2143: syntax error : missing ')' before '&'


Hi,
I am a C++ newbie and had never written even a very simple C++ class before. Now I intend to do such a job. My objective is quite simple, a matrix class with the following features is just OK:
1. The object of such a class can be initialized by the data stored in a disk file and as a side information, the size of the desired matrix will be provided.
2. The summation of all the elements in the matrix should be obtained conveniently.

I have spend almost 2 days on this job and the following is my "achievement":
1. The definition of the class is included in a header file "matrix.h":
CPP / C++ / C Code:
#include <fstream>
#include <vector>

typedef unsigned long ULONG;
class CMatrix
{
public:
	CMatrix(ifstream &in_file,int row,int col);    // Initialize(or construct) an matrix object with the data in a
	                                               // file, the width and the height of the matrix are both given.  
	ULONG sum();                                   // Get the summation of all the elements in the matrix.
	int s_row();                                   // Get the number of rows of the matrix, which may be trivial since 
	                                               // all the dimension information are already given as the argument of 
	                                               // constructor, but this may be more of "a member function",just a try.  
	int s_col();                                   // Get the number of the columns of the matrix.
private:
	vector<short>& base_row;      
	vector< vector<short> >& base_mat;   // Where all the elements of matrix are located.
};

CMatrix::CMatrix(ifstream &in_file, int row, int col)
{
	short val;
	while (in_file.read(reinterpret_cast<char*>(&val),sizeof(short)))
	{
		for (int rn=0; rn<row; rn++)
		{
			for (int cn=0; cn<col; cn++)
			{
				base_row.push_back(val);
			}
			base_mat.push_back(base_row);
			base_row.clear();
		}
	}
}

int CMatrix::sum()
{
	int _sum_1d = 0;
	int _sum_2d = 0;
	for (vector< vector<short> >::iterator it_2d = base_mat.begin(); it_2d<base_mat.size(); it_2d++)
	{
		for (vector<short>::iterator it_1d = base_row.begin(); it_1d<base_row.size(); it_1d++)
		{
			_sum_1d = _sum_1d + (*it_1d);  
		}
		_sum_2d = _sum_2d + _sum_1d;
	}
	return _sum_2d;
}

int CMatrix::s_row()
{
	return static_cast<int>(base_mat.size());
}

int CMatrix::s_col()
{
	return static_cast<int>(base_row.size());
}
2. The application using this class is included in a cpp file "matrix.cpp":
CPP / C++ / C Code:
#include <iostream>
#include <string>
#include "matrix.h"

using namespace std;

int main(int argc, char** argv)
{
	if (argc!=2)
	{
		cout<<"Input error!"<<endl;
		cout<<"matrix_class.exe in_file"<<endl;
		exit(EXIT_FAILURE);
	}
	ifstream in_file(argv[1], ios::binary);     // argv[1] is the name of the file storing 9 numbers of short type and as a result the size is 18 BYTES.
	CMatrix myMat(in_file,3,3);
	cout<<"The sum of the matrix stored in file "<<argv[1]<<" is "<<myMat.sum()<<endl;
}
The necessary comments are already included in the code snippets.When I build the project in VS2005, as much as 40 errors are reported:
Code:
e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(8) : error C2143: syntax error : missing ')' before '&' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(8) : error C2143: syntax error : missing ';' before '&' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(8) : error C2460: 'CMatrix::ifstream' : uses 'CMatrix', which is being defined e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(6) : see declaration of 'CMatrix' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(8) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(8) : error C2062: type 'int' unexpected e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(16) : error C2143: syntax error : missing ';' before '<' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(16) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(16) : error C2238: unexpected token(s) preceding ';' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(17) : error C2143: syntax error : missing ';' before '<' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(17) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(17) : error C2238: unexpected token(s) preceding ';' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(20) : error C2065: 'in_file' : undeclared identifier e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(20) : error C2597: illegal reference to non-static member 'CMatrix::ifstream' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(20) : error C2062: type 'int' unexpected e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(21) : error C2143: syntax error : missing ';' before '{' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(21) : error C2447: '{' : missing function header (old-style formal list?) e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(38) : error C2556: 'int CMatrix::sum(void)' : overloaded function differs only by return type from 'ULONG CMatrix::sum(void)' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(10) : see declaration of 'CMatrix::sum' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(38) : error C2371: 'CMatrix::sum' : redefinition; different basic types e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(10) : see declaration of 'CMatrix::sum' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2065: 'vector' : undeclared identifier e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2062: type 'short' unexpected e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2039: 'iterator' : is not a member of '`global namespace'' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2065: 'it_2d' : undeclared identifier e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2065: 'base_mat' : undeclared identifier e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2228: left of '.size' must have class/struct/union type is ''unknown-type'' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2143: syntax error : missing ';' before ')' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(41) : error C2143: syntax error : missing ';' before ')' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(42) : error C2143: syntax error : missing ';' before '{' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(43) : error C2062: type 'short' unexpected e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(43) : error C2039: 'iterator' : is not a member of '`global namespace'' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(43) : error C2065: 'it_1d' : undeclared identifier e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(43) : error C2065: 'base_row' : undeclared identifier e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(43) : error C2228: left of '.size' must have class/struct/union type is ''unknown-type'' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(43) : error C2143: syntax error : missing ';' before ')' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(43) : error C2143: syntax error : missing ';' before ')' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(44) : error C2143: syntax error : missing ';' before '{' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(54) : error C2228: left of '.size' must have class/struct/union type is ''unknown-type'' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.h(59) : error C2228: left of '.size' must have class/struct/union type is ''unknown-type'' e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.cpp(16) : error C2078: too many initializers e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.cpp(16) : error C2440: 'initializing' : cannot convert from 'int' to 'CMatrix' No constructor could take the source type, or constructor overload resolution was ambiguous e:\code zone\practice code\my_first_class\matrix_class\matrix_class\matrix.cpp(17) : error C2264: 'CMatrix::sum' : error in function definition or declaration; function not called
I know it may seem lazy for me to paste all the code without localizing the potential errors. But by now that's really beyond my capability. Any one can tell me where things goes wrong and how to fix them? thank u in advance.
  #2  
Old 14-Jul-2009, 22:48
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 802
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: Help!My first C++ class is messed up!


How could you write so much stuff without testing along the way?
I would suggest you drop back to this and add / fix things until you're stumped and then ask:
CPP / C++ / C Code:
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

typedef unsigned long ULONG;

class CMatrix
{
  private:
    vector<short>& base_row;
    vector< vector<short> >& base_mat;

  public:
    CMatrix(ifstream &in_file, int row, int col);
};

int main(void)
{
  return 0;
}
  #3  
Old 15-Jul-2009, 00:36
Kimmo Kimmo is offline
Member
 
Join Date: Mar 2007
Location: Finland
Posts: 285
Kimmo is a jewel in the roughKimmo is a jewel in the roughKimmo is a jewel in the rough

Re: Help!My first C++ class is messed up!


As Howard suggests, perhaps you should take a peek at some reading about namespaces. Naturally, you can also tack the "using namespace std;" in the beginning of your files without knowing what it's for, but it's nice to know what actually it's for and what are the alternatives.

Why are your class data members base_row and base_mat references? Your constructor does a whole lot of work that would be better left to a dedicated member function. Besides, with your reference class members in place, there's no way you can construct your matrix that way.

It makes sense if the constructor takes an argument of the type of your matrix. Or it makes sense if you have a member function addRow(vector<short>&), which adds a new row to the matrix. But for me it makes little sense to make the constructor start reading from files.

Why are you static_cast'ing the return value from the vector's size()? What if the size is larger than what your int can hold? Probably unlikely, but one can wonder why return an int to begin with when the return value from size() is not an int.

The declaration of sum() says it returns an unsigned long, but the definition says it returns an int.

The base_row data member is useless. You only use it as a temporary variable to store a matrix row before writing it to base_mat. You could just use a real temporary variable in the method that reads the file. If you need the dimensions of the vector, then you can simply store them in separate data members, for example.

This
CPP / C++ / C Code:
for (vector< vector<short> >::iterator it_2d = base_mat.begin(); it_2d<base_mat.size(); it_2d++)
could (should?) be written as
CPP / C++ / C Code:
for (vector< vector<short> >::iterator it_2d = base_mat.begin(); it_2d != base_mat.end(); it_2d++)
This is how one usually uses iterators. I haven't taken any looks at the insides of iterators, but I'm wary of the way to test if the iterator is, for example, 5.

I decided to make a simple test program and ran it with gdb. Here are the results. it is an iterator, vint is a vector.

Code:
(gdb) print it $2 = {_M_current = 0x33fc8} (gdb) print vint.begin() $3 = {_M_current = 0x33fc8} (gdb) print vint.end() $4 = {_M_current = 0x33fcc} (gdb) print vint.size() $5 = 1 (gdb)
According to this it's not a good idea to test the iterator with index values. Of course, perhaps vector<T>::iterator has overloaded comparison operators to compare with index values, but this is unlikely in my opinion, considering how many overloads you'd need and when you already have a simple end().


Quote:
I know it may seem lazy for me to paste all the code without localizing the potential errors. But by now that's really beyond my capability.
It's like building a house and after it's finished, taking the first look at what you've done. You realize it's already almost falling apart and you can either try to fix it, ending up with something you don't have the time to keep fixing or you can call in the professionals to level your house and build it anew like it should've been built.

You just don't do it. You do what Howard said.
  #4  
Old 20-Jul-2009, 04:15
Kimmo Kimmo is offline
Member
 
Join Date: Mar 2007
Location: Finland
Posts: 285
Kimmo is a jewel in the roughKimmo is a jewel in the roughKimmo is a jewel in the rough

Re: Error C2143: syntax error : missing ')' before '&'


Sorry for the late follow-up, but something I didn't notice the first time in your implementation.

CPP / C++ / C Code:
int CMatrix::sum()
{
	int _sum_1d = 0;
	int _sum_2d = 0;
	for (vector< vector<short> >::iterator it_2d = base_mat.begin(); it_2d<base_mat.size(); it_2d++)
	{
		for (vector<short>::iterator it_1d = base_row.begin(); it_1d<base_row.size(); it_1d++)
		{
			_sum_1d = _sum_1d + (*it_1d);  
		}
		_sum_2d = _sum_2d + _sum_1d;
	}
	return _sum_2d;
}
Apart from what I already said about the use of iterators, your inner for loop cannot be implemented that way. Your base_row would always hold the last row added to the matrix and thus your sum() method would get the values from the last row added. It would just add those values every time your inner loop runs. Also, you should set _sum_1d to 0 in the start of your outer loop to get the correct results.

Anyway, here is one possible start for a matrix class based on what I said earlier.

matrix.h:
CPP / C++ / C Code:
#ifndef MATRIX_H
#define MATRIX_H

// Forward declaration for vector class
class vector;

class Matrix
{
    public:
    
        // Default constructor, initializes m_rows and m_cols to 0
        Matrix();
        // Sets rows and columns
        Matrix(size_t rows, size_t cols);
        // Sets matrix
        Matrix(const std::vector<std::vector<short> >& matrix);
        // Sets rows, columns and matrix
        Matrix(const std::vector<std::vector<short> >& matrix,
               size_t rows, size_t cols);
        
        // Adds new row to matrix
        // Does not modify m_rows. setRowAmount() or
        // setDimensions() should be called after adding row
        void addRow(const std::vector<short>& row);
        
        // Sets matrix
        void setMatrix(const std::vector<std::vector<short> >& matrix);
        // Sets number of rows
        void setRowAmount(const size_t rows);
        // Sets number of columns
        void setColAmount(const size_t cols);
        // This method will set m_rows and m_cols based on
        // currently defined m_matrix
        void setDimensions();
        void setDimensions(size_t rows, size_t cols);
                
        size_t rowAmount() const;
        size_t colAmount() const;
        // Returns the total of all elements in matrix
        unsigned long sum();
        
    private:
    
        size_t m_rows;
        size_t m_cols;
        std::vector<std::vector<short> > m_matrix;
        
}; // class Matrix

#endif // MATRIX_H

matrix.cpp
CPP / C++ / C Code:
#include <vector>
#include "matrix.h"

Matrix::Matrix()
    : m_rows(0), m_cols(0)
{
}

Matrix::Matrix(size_t rows, size_t cols)
    : m_rows(rows), m_cols(cols)
{
}

Matrix::Matrix(const std::vector<std::vector<short> >& matrix)
    : m_matrix(matrix)
{
}

Matrix::Matrix(const std::vector<std::vector<short> >& matrix,
               size_t rows, size_t cols)
    : m_rows(rows), m_cols(cols), m_matrix(matrix)
{
}

void Matrix::addRow(const std::vector<short>& row)
{
    m_matrix.push_back(row);
}

void Matrix::setMatrix(const std::vector<std::vector<short> >& matrix)
{
    m_matrix = matrix;
}

void Matrix::setRowAmount(size_t rows)
{
    m_rows = rows;
}

void Matrix::setColAmount(size_t cols)
{
    m_cols = cols;
}

void Matrix::setDimensions()
{
    m_rows = m_matrix.size();
    m_cols = m_matrix[0].size();
}

void Matrix::setDimensions(size_t rows, size_t cols)
{
    m_rows = rows;
    m_cols = cols;
}

size_t Matrix::rowAmount() const
{
    return m_rows;
}

size_t Matrix::colAmount() const
{
    return m_cols;
}

unsigned long Matrix::sum()
{
    using std::vector;
    
    unsigned long _sum_1d = 0;
    unsigned long _sum_2d = 0;
    for (vector<vector<short> >::iterator it_2d = m_matrix.begin(); it_2d != m_matrix.end(); it_2d++)
    {
        _sum_1d = 0;
        for (vector<short>::iterator it_1d = it_2d->begin(); it_1d != it_2d->end(); it_1d++)
        {
            _sum_1d = _sum_1d + (*it_1d);
        }
        _sum_2d = _sum_2d + _sum_1d;
    }
    return _sum_2d;
}
Here note that it_2d is an iterator that points to a row in the matrix. When you increment it, you go to the next row. Thus, it_2d->begin() is the start of the row.

main.cpp
CPP / C++ / C Code:
#include <vector>
#include <iostream>

#include "matrix.h"

int main()
{
    using std::vector;
    using std::cout;
    using std::endl;

    short rowVal = 234;
    short colVal = 2;
    short val = 0;
    unsigned long matrixSum = 0;
    
    int rows = 3;
    int cols = 3;
    
    vector<vector<short> > vectorMatrix;
    
    for (int i = 0; i < rows; i++)
    {
        vectorMatrix.push_back(vector<short>());
        for (int j = 0; j < cols; j++)
        {
            val = rowVal + colVal;
            rowVal += 2;
            colVal *= 2;
            matrixSum += val;
            cout << "val at i(" << i << "), j(" << j << ") = " << val << endl;
            vectorMatrix[i].push_back(val);
        }
    }
    
    Matrix matrixMatrix1(vectorMatrix, rows, cols);
    
    cout << "matrixSum = " << matrixSum << endl;
    cout << "matrixMatrix1.sum() = " << matrixMatrix1.sum() << endl;
    cout << endl;
    
    cout << "Creating a new matrix with Matrix()" << endl;
    Matrix matrixMatrix2;
    cout << "Using setMatrix(vector<vector<short> >) to set matrix" << endl;
    matrixMatrix2.setMatrix(vectorMatrix);
    cout << "Setting matrix dimensions with setDimensions()" << endl;
    matrixMatrix2.setDimensions();
    cout << "Number of rows is " << matrixMatrix2.rowAmount() << endl;
    cout << "Number of columns is " << matrixMatrix2.colAmount() << endl;
    cout << "Adding a new row "
    " {2, 4, 6} to matrixMatrix2 with addRow(vector<vector<short> >)" << endl;
    
    vector<short> newRow(3);
    newRow[0] = 2; newRow[1] = 4; newRow[2] = 6;
    matrixMatrix2.addRow(newRow);
    
    cout << "matrixMatrix1.sum() now " << matrixMatrix1.sum() << endl;
    cout << "matrixMatrix2.sum() now " << matrixMatrix2.sum() << endl;
    cout << "Setting new dimensions for matrixMatrix2 with setDimensions()" << endl;
    matrixMatrix2.setDimensions();
    cout << "matrixMatrix2.rowAmount() now " << matrixMatrix2.rowAmount() << endl;
    cout << "matrixMatrix2.colAmount() now " << matrixMatrix2.colAmount() << endl;
       
    return 0;
}

Some things to note.

There is no error checking of any kind. This also includes the forcing of the matrix dimensions. That is, there is nothing that prevent you from creating a 3x3 matrix and then adding a row with 50 columns. You could easily implement this by, for example, making m_rows and m_cols const. You would then have to pass the dimensions in a constructor since you cannot assign const members.
CPP / C++ / C Code:
Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {}
Then you would simply check that all rows are exactly that long and that there are exactly that many rows when defining the matrix.

I didn't implement creating a matrix from a file since I don't think the Matrix class should do such a thing. For this you could define a global function or a class with a static method that reads the file and returns a vector<vector<short> > or a Matrix object.
For example:
CPP / C++ / C Code:
Matrix createMatrix(std::string filename, size_t rows, size_t cols);
Or
CPP / C++ / C Code:
class MatrixMaker // a "media sexy" name
{
    public:
        static Matrix createMatrix(std::string filename, size_t rows, size_t cols);
}
It doesn't make much difference which you choose, though if you implement several Matrix-handling functions it might be convenient to wrap them all inside a MatrixHandler class or something.
 
 

Recent GIDBlogProblems with the Navy (Chiefs) 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
Returning a Struct to a separate class usmsci C++ Forum 9 07-Feb-2007 09:34
Hard drive/CPU Diagnoses Issues binarybug Computer Hardware Forum 1 22-Jan-2007 20:23
Box Class, need help again :( TransformedBG C++ Forum 7 13-Nov-2006 16:11
C++ class -- Please help vnca_1 C++ Forum 3 14-Jun-2006 13:31
a tester class and then some. postage Java Forum 1 06-May-2006 16:48

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

All times are GMT -6. The time now is 13:53.


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