Hi, I'm making a matrix class and I'm currently trying to overload some operators.

+=

#ifndef MATRIX_H
#define MATRIX_H

#include <iostream>
#include <ostream>
#include <string>
#include <sstream>

class Matrix
{
	Matrix& operator = (const Matrix &m);
	
	Matrix& operator += (const Matrix &m);

public:
	Matrix(int x, int y);
	Matrix(Matrix &m);
	~Matrix();

	void Init();
	void Display() const;

	int get_x() const;
	int get_y() const;
	const int * const get_p() const;
	
private:
	bool isInitialized;

	int x, y;
	int *p; // pointer to the matrix
};

#endif // MATRIX_H
Matrix& Matrix::operator +=(const Matrix &m)
{	
	if(x == m.get_x() && y == m.get_y())
	{
		for(int i = 0; i < x; ++i)
			for(int j = 0; j < y; ++j)
				*(p + (i * y) + j) = *(m.get_p() + (i * y) + j);
	}
	return *this;
}

and in main:

#include <iostream>

#include "matrix.h"

using std::cout;	using std::cin;

int main()
{
	Matrix a(2, 2); a.Init();
	Matrix b(2, 2); b.Init();
	
	b += a;
	b.Display();

	system("pause");
	return 0;
}

and I get:

1>c:\users\user\documents\visual studio 2008\projects\matrices\matrices\main.cpp(12) : error C2248: 'Matrix::operator +=' : cannot access private member declared in class 'Matrix'
1> c:\users\user\documents\visual studio 2008\projects\matrices\matrices\matrix.h(13) : see declaration of 'Matrix::operator +='
1> c:\users\user\documents\visual studio 2008\projects\matrices\matrices\matrix.h(10) : see declaration of 'Matrix'
1>Build log was saved at "file://c:\Users\User\Documents\Visual Studio 2008\Projects\Matrices\Matrices\Debug\BuildLog.htm"

I'm not trying to access a private member, am I? And it should be working as well,because I'm doing it from inside the class. Something else is Wrong I think.

Why? I'm getting there values from the functions get_x, get_y and get_p.

By default class definition body starts with private zone. So you declare both operator= and operator+= as private members of Matrix (look again at you class Matrix). Well, you can't access them outside Matrix member functions and friends of the Matrix class. But your main function is not a friend of Matrix...

Why do you cry now? ;)

This article has been dead for over six months. Start a new discussion instead.