error: variable has initializer and is incomplete

Jun 21, 2009 at 7:01pm
I just started to try and write a matrix class library and ran into a compiler error that I don't understand. So far I have two files for the library, one that deals with the class and member functions and another that has functions that operate on matrices, but I don't really see a reason to make member functions.

The error concerns the function below.
error: return type struct Matrix<int> incomplete.
error: variable 'Matrix<int> I' has initializer but incomplete type.

The compiler then tells me it is bailing out. the compiler is g++


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<cmath>
#include<iostream>
#include<string>

template<typename T> class Matrix;

Matrix<int> eye(int size)//Error here
{
	int SIZE=size*size;
	Matrix<int> I(size, size);//Error here
	for(int i=0;i<SIZE;i+=(size+1))
		I(i)=1;
	return I;
}


The class specification

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template<typename T>
class Matrix
{
	public:
		int numR, numC;
		T *numbers;
	public:
		Matrix(int,int);
		void print();
		T &operator()(int);
		T &operator()(int, int);
		
		template<typename S>
			Matrix<T> &operator=(Matrix<S>);
		template<typename S>
			Matrix<T> &operator+=(Matrix<S>);
		template<typename S>
			Matrix<T> &operator+=(S);
		template<typename S>
			Matrix<T> &operator-=(Matrix<S>);
};


The relevant constructor

1
2
3
4
5
6
7
template<typename T>
Matrix<T>::Matrix(int rows, int cols)
{
	numR=rows;
	numC=cols;
	numbers = new T[rows*cols];
}


And the Operator= function if necessary

1
2
3
4
5
6
7
8
9
10
11
template<typename T>
	template<typename S>
Matrix<T> &Matrix<T>::operator=(Matrix<S> other)
{
	numR=other.numR;
	numC=other.numC;
	int i, size=numR*numC;
	for(i=0;i<size;i++)
		numbers[i]=other(i);
	return *this;
}


Does anybody know what i am doing wrong or a resource that will help me with this problem?
Last edited on Jun 21, 2009 at 7:09pm
Jun 21, 2009 at 7:06pm
it would help if you told us what line the error was on.

Also:

[code]
Put your code in code tags like this
[/code]

EDIT:

Oh wait, I see it.

You're trying to instantiate your matrix class, but you never defined it (gave it a body), you only forward declared it. Forward declaring enough to be able to make a matrix object, the compiler needs to see the whole class.

Move your 'eye' function so that it's below your matrix class body. Or better yet -- reorganize and make proper .h and .cpp files for this class so you avoid messy code disasters.

EDIT 2:

Crap thought all of that was the same .cpp file XD. Addition of code tags clarified it. Sorry about that.

Anyway, instead of forward declaring in that first code snippit, #include your matrix.h file
Last edited on Jun 21, 2009 at 7:11pm
Jun 21, 2009 at 7:16pm
That fixed the problem, thanks
Topic archived. No new replies allowed.