Pablo Jeken Rico
Pablo Jeken Rico

Reputation: 579

Expected id-expression - Compiling with g++

I just wrote a program with a Matrix object inside the main.cpp file. Everything was fine.

Now I want to outsource the object into a Matrix.cpp file and Matrix.h header, but I have encountered an error.

I get the following compiler error:

Matrix.cpp:5:15: error: expected id-expression before '(' token Matrix::Matrix(int n_rows){

Matrix.h:

#ifndef Matrix
#define Matrix
#include "iostream"
#include "string"
#include <sstream>
#include <cstdlib>
using namespace std;

class Matrix{

  private:

    int n_rows;
    int* vect;

  public:
    Matrix(int);
};

#endif

Matrix.cpp:

#include "Matrix.h"

// Constructor
Matrix::Matrix(int n_rows){ //ERROR
    if(n_rows>0){

    this->n_rows = n_rows;
    this->vect = new int[n_rows];
    srand(time(NULL));

    for(int i = 0; i< n_rows; i++){
        this->vect[i] = rand() % 100;
        }
    }   
}

Maybe there is a keyword to this problem that I do not know jet. I would appreciate it if you could help me out.

NEW: Based on the accepted answer: Why is the the occurence Matrix substituted by a blank space?

Upvotes: 0

Views: 3699

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

#define Matrix means that every occurrence of 'Matrix' will be replaced with nothing by the preprocessor.

Thus, your compiler sees this

using namespace std;

class {

  private:

    int n_rows;
    int* vect;

  public:
    (int);
};

::(int n_rows){ 
    if(n_rows>0){

    this->n_rows = n_rows;
    this->vect = new int[n_rows];
    srand(time(NULL));

    for(int i = 0; i< n_rows; i++){
        this->vect[i] = rand() % 100;
        }
    }   
}

But the error message refers to the code before preprocessing, which makes it pretty incomprehensible.

Include guards are conventionally all uppercase (as are macros in general).
You should do that, too.

#ifndef MATRIX_H
#define MATRIX_H

Upvotes: 3

Related Questions