Консультация № 166745
07.05.2009, 21:56
0.00 руб.
0 17 1
Здраствуйте! Мне очень нужна помощь.. мне сказали спрограммировать программу: "Арифметика комплексных чисел". Класс матриц я у вас посмотрела. однако я не понимаю, как же связать класс комплексных чисел с марицей... нужно было делать в классе.. Подскажите пожалуйста..класс комплексных матриц(ошибки есть и не доделана до конца) у меня есть.

Приложение:
//Complex.cpp

#include <stdio.h>
#include <iostream>
#include <math.h>
#include "Complex.h"
#include "Matrix.h"
using namespace std;


Complex Complex::operator+(Complex &f1)// Перегрузка +
{
f1.real = real + f1.real;
f1.image = image + f1.image;
return f1;
}

Complex Complex::operator-(Complex &f1)// Перегрузка -
{
f1.real = real - f1.real;
f1.image = image - f1.image;
return f1;
}

Complex Complex::operator*(Complex &f1)// Перегрузка *
{
double i, j;
image = real * f1.real - image * f1.image;
return f1;
}


/*Complex::Complex(double r, double i)
{
m_re=re;
m_im=im;

}*/
/* Complex & Complex::operator*(Сomplex f1)//перегрузка бинарных операторов
{
return Сomplex(real*f1.real-image*f1.image,real*f1.image-image*f1.real);
}*/
//Сomplex Сomplex::operator~()//сопряжение

//{

//return Сomplex(m_re, -m_im);

//}

Complex & Complex::operator=(const Complex &f1)
{
real=f1.real;
image=f1.image;
return *this;
}

Complex & Complex::operator*=(Complex f1)
{
Complex temp=*this;
real=temp.real*f1.real-temp.image*f1.image;
image=temp.real*f1.image+temp.image*f1.real;
return (*this);,
}

Complex & Complex::operator=(const Complex& f1)
{
real=other.real;
image=other.image;
return *this;
}

Сomplex & Сomplex::operator*=(Сomplex other)
{
Сomplex temp=*this;
real=temp.real*other.real-temp.image*other.image;
image=temp.real*other.image+temp.image*other.real;
return (*this);
}

/*Сomplex::operator double() const // преобразование
{
return (r*r-i*i);
}*/

ostream & operator<< (ostream& out, Complex x)
{
return (out<<"("<<x.real<<","<<x.image<<")");
}

istream & operator<< (istream& out, Complex x)
{
return (in>>x.real<<x.image);
}

bool Complex::operator== (complex other)//логические операторы
{
if(real == other.real && image == other.image)
{
return true;
}
return false;
}

/*void Point::Show()const
{
cout<<x<<':'<<y;
};
void Point::operator+=(Point &p)
{
x=x+p.x;
y=y+p.y;
}
Point Point::
operator+(Point &p)
{
return Point(x + p.x,y + p.y);
}

Point Point::
operator-(Point &p)
{
return Point(x - p.x,y - p.y);
}

double Point:: Length() const
{
return sqrt(x*x + y*y);
}


ORIENT Point::or(Point &b, Point &e) const
{
Point p0=*this;
Point a = e-b;
Point c = p0-b;
double s=
a.x*c.y-a.y*c.x;
if(s<0)
return Right;
if(s>0)
return Left;
if(((a.x*c.x) < 0) || ((a.y*c.y) < 0))
return Behind;
if(a.Length()> c.Length())
return On;
return Ahead;
}

bool Point::InTriangle(Triangle &T) const
{

ORIENT or1 = or(T.Get_v1(),T.Get_v2());
ORIENT or2 = or(T.Get_v2(),T.Get_v3());
ORIENT or3 = or(T.Get_v3(),T.Get_v1());
if((or1==Right || or1==On)&&
(or2==Right || or2==On)&&
(or3==Right || or3==On))
return 1;
return 0;
}
*/







// Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
//enum ORIENT {Left,Right,Behind, Ahead, On};
class Matrix;
class Complex
{
private:
double real; // Действительная часть
double image;// Мнимая часть
public:

Complex(double r=0, double i=0) { real = r, image = i; } // Конструктор
double abs() // Модуль комплексного числа
{
return sqrt(real * real - image * image);
}
Complex operator+(Complex &); // Перегрузка оператора сложения
Complex operator-(Complex &); // Перегрузка оператора вычитания
Complex operator*(Complex &); // Перегрузка оператора умножения
// Complex operator- ();
bool operator== (Complex &);
bool operator!= (Complex &);
// friend ostream & operator<<(ostream &, Complex &);// Перегрузка функции-оператора << для вывода класса Complex
// friend istream & operator>>(istream &, Complex &); // Перегрузка функции-оператора >> для ввода класса Complex

//operator double() const;//преобразование
//Complex(double , double );


/*double x,y;
void operator+=(Point &);
Point operator+(Point &);
Point operator-(Point &);
double Point:: Length() const;
ORIENT or(Point &, Point &) const;
bool InTriangle(Triangle &)
const;*/
};
#endif



Обсуждение

Неизвестный
08.05.2009, 00:53
общий
Лучше определить класс как шаблон типа
template<class T>
class matrix
{
...
}

Тогда можно матрицы любого типа делать.
Можно сделать матрицу и так
Код:

#include <complex>
#include <vector>

vector< vector<complex> > complexMatrix;

А вообще в чем вопрос то? А то я класса комплексных матриц так и не увидел(впрочем и не комплексных тоже).
Неизвестный
08.05.2009, 09:23
общий
я не создала еще класс комплексных матриц, вот именно... не понимаю как создать..
Неизвестный
09.05.2009, 10:24
общий
это ответ
Здравствуйте, Кашапова Аиша Рифгатовна!
Вот пример шаблонного класса для матриц и комплексных чисел. Функционал добавьте сами какой требуется. Тестировал MS VS 2008.
Код:

#include <locale>
#include <valarray>
#include <ios>
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <ctime>
#include <cstdlib>

using namespace std;

#pragma region Класс complex декларация
class complex
{
public:
// Конструктор
complex(double re=0, double im=0);
// Оператор ()
complex& operator()(double re=0, double im=0);
complex& operator()(const complex& val);
// Оператор "равно"
bool operator==(const complex& val) const;
// Оператор "не равно"
bool operator!=(const complex& val) const;
// Возвращает действительную часть
double re(void) const;
static double re(const complex& val);
// Возвращает мнимую часть
double im(void) const;
static double im(const complex& val);
// Выделение модуля
double abs(void) const;
static double abs(const complex& val);
// Аргумент
double arg(void) const;
static double arg(const complex& val);
// Оператор сложения
friend complex operator+(const complex& val1,const complex& val2);
complex& operator+=(const complex& val);
// Оператор вычитания
friend complex operator-(const complex& val1,const complex& val2);
complex& operator-=(const complex& val);
// Оператор умножения
friend complex operator*(const complex& val1,const complex& val2);
complex& operator*=(const complex& val);
// Опрератор деления
friend complex operator/(const complex& val1,const complex& val2);
complex& operator/=(const complex& val);
// Возведение в степень
friend complex pow(const complex& val,double deg);
// Извлечение квадратного корня
friend complex sqrt(const complex& val);
// Операторы ввода/вывода
friend ostream& operator<<(ostream& stream,const complex& val);
friend istream& operator>>(istream& stream,complex& val);
private:
double _re;
double _im;
};
#pragma endregion

#pragma region class matrix
template<class T>
class matrix
{
class _row;
public:
// Конструктор создающий матрицу с rows-строками и cols-колонками
matrix(unsigned int rows,unsigned int cols);
// Конструктор копирования
matrix(const matrix<T>& matr);
// Оператор присваивания
matrix<T>& operator=(const matrix<T>& matr);
// Деструктор
virtual ~matrix();
_row& operator[](unsigned int row);
// Возвращает количество строк
unsigned int rows() const;
// Возвращает количество колонок
unsigned int cols() const;
private:
class _row
{
public:
T& operator[](unsigned int col);
private:
_row(unsigned int cols);
_row(const typename matrix<T>::_row& r);
_row& operator=(const typename matrix<T>::_row& r);
virtual ~_row();
T* _data;
unsigned int _cols;
friend class matrix;
};
_row** _data;
unsigned int _rows,_cols;
};
#pragma endregion class matrix

int rnd(int hi)
{
return static_cast<int>(static_cast<double>(rand())/RAND_MAX*hi);
}

int main()
{
srand(static_cast<unsigned int>(time(0)));
const unsigned int ROWS=5,COLS=8;
matrix<complex> arr(ROWS,COLS);
for(unsigned int i=0;i<arr.rows();++i)
{
for(unsigned int j=0;j<arr.cols();++j)
{
arr[i][j]=complex(rnd(20)-10,rnd(20)-10);
}
}
matrix<complex> arr2(arr);
arr=arr2;
for(unsigned int i=0;i<arr.rows();++i)
{
for(unsigned int j=0;j<arr.cols();++j)
{
cout<<arr[i][j]<<' ';
}
cout<<endl;
}
system("PAUSE");
return 0;
}

#pragma region Класс matrix определение
template<class T>
matrix<T>::matrix(unsigned int rows, unsigned int cols)
:_rows(rows)
,_cols(cols)
,_data(0)
{
_data=new _row*[_rows];
for(unsigned int i=0;i<_rows;++i)
{
_data[i]=new _row(_cols);
}
}

template<class T>
matrix<T>::matrix( const matrix<T>& matr )
:_rows(matr._rows)
,_cols(matr._cols)
,_data(0)
{
_data=new _row*[_rows];
for(unsigned int i=0;i<_rows;++i)
{
_data[i]=new _row(_cols);
*(_data[i])=*(matr._data[i]);
}
}

template<class T>
matrix<T>& matrix<T>::operator=( const matrix<T>& matr )
{
if(&matr!=this)
{
if(_data)
{
for(unsigned int i=0;i<_rows;++i)
{
delete _data[i];
}
delete []_data;
}
_rows=matr._rows;
_cols=matr._cols;
_data=new _row*[_rows];
for(unsigned int i=0;i<_rows;++i)
{
_data[i]=new _row(_cols);
*_data[i]=*matr._data[i];
}
}
return *this;
}

template<class T>
matrix<T>::~matrix()
{
if(_data)
{
for(unsigned int i=0;i<_rows;++i)
{
if(_data[i])delete _data[i];
}
delete []_data;
}
}

template<class T>
typename matrix<T>::_row& matrix<T>::operator[](unsigned int row)
{
if(row<_rows)return *_data[row];
else throw range_error("Bound(row) out of range");
}

template<class T>
inline unsigned int matrix<T>::cols() const
{
return _cols;
}

template<class T>
inline unsigned int matrix<T>::rows() const
{
return _rows;
}


template<class T>
matrix<T>::_row::~_row()
{
if(_data)delete []_data;
}

template<class T>
typename matrix<T>::_row& matrix<T>::_row::operator=(const typename matrix<T>::_row& r )
{
if(&r!=this)
{
if(_data)delete []_data;
_cols=r._cols;
_data=new T[_cols];
for(unsigned int i=0;i<_cols;++i)
{
_data[i]=r._data[i];
}
}
return *this;
}

template<class T>
matrix<T>::_row::_row(const typename matrix<T>::_row& r )
:_cols(r._cols)
,_data(0)
{
_data=new T[_cols];
for(unsigned int i=0;i<_cols;++i)
{
_data[i]=r._data[i];
}
}

template<class T>
matrix<T>::_row::_row( unsigned int cols )
:_cols(cols)
,_data(0)
{
_data=new T[cols];
}

template<class T>
T& matrix<T>::_row::operator [](unsigned int col)
{
if(col<_cols)return _data[col];
else throw range_error("Bound(col) out of range");
}
#pragma endregion Класс matrix определение

#pragma region Класс complex определение
// Конструктор
inline complex::complex(double re, double im)
: _re(re)
, _im(im)
{
}

inline complex& complex::operator()(double re, double im)
{
_re=re;
_im=im;
return *this;
}
inline complex& complex::operator ()(const complex& val)
{
_re=val._re;
_im=val._im;
return *this;
}

ostream& operator<<(ostream& stream,const complex& val)
{
if(val._re||!val._im)stream<<val._re;
if(val._im)
{
ios_base::fmtflags flags=stream.flags();
if(val._re)stream.setf(ios::showpos);
stream<<val._im<<'i';
stream.flags(flags);
}
return stream;
};

istream& operator>>(istream& stream,complex& val)
{
double re,im;
stream>>re>>im;
if(stream.good())
{
val._re=re;
val._im=im;
}
return stream;
};
inline bool complex::operator==(const complex& val) const
{
return (_re==val._re)&&(_im==val._im);
}

inline bool complex::operator!=(const complex& val) const
{
return (_re!=val._re)||(_im!=val._im);
}

// Возвращает действительную часть
inline double complex::re(void) const
{
return _re;
}
inline double complex::re(const complex& val)
{
return val._re;
}

// Возвращает мнимую часть
inline double complex::im(void) const
{
return _im;
}
inline double complex::im(const complex& val)
{
return val._im;
}

// Оператор сложения
inline complex operator+(const complex& val1,const complex& val2)
{
return complex(val1._re+val2._re,val1._im+val2._im);
}
inline complex& complex::operator+=(const complex& val)
{
_re+=val._re;
_im+=val._im;
return *this;
}

// Оператор вычитания
inline complex operator-(const complex& val1,const complex& val2)
{
return complex(val1._re-val2._re,val1._im-val2._im);
}
inline complex& complex::operator-=(const complex& val)
{
_re-=val._re;
_im-=val._im;
return *this;
}

// Оператор умножения
complex operator*(const complex& val1,const complex& val2)
{
return complex(val1._re*val2._re-val1._im*val2._im,val1._re*val2._im+val1._im*val2._re);
}
complex& complex::operator*=(const complex& val)
{
_re=_re*val._re-_im*val._im;
_im=_re*val._im+_im*val._re;
return *this;
}

// Опрератор деления
complex operator/(const complex& val1,const complex& val2)
{
double div=val2._re*val2._re+val2._im*val2._im;
return complex((val1._re*val2._re+val1._im*val2._im)/div,(val1._im*val2._re-val1._re*val2._im)/div);
}
complex& complex::operator/=(const complex& val)
{
double div=val._re*val._re+val._im*val._im;
_re=(_re*val._re+_im*val._im)/div;
_im=(_im*val._re-_re*val._im)/div;
return *this;
}

// Выделение модуля
inline double complex::abs(void) const
{
return std::sqrt(_re*_re+_im*_im);
}
inline double complex::abs(const complex& val)
{
return std::sqrt(val._re*val._re+val._im*val._im);
}

// Аргумент
inline double complex::arg(void) const
{
return acos(_re/abs());
}
inline double complex::arg(const complex& val)
{
return acos(val._re/val.abs());
}

complex pow(const complex& val,double deg)
{
double r=std::pow(val.abs(),deg),a=val.arg()*deg;
return complex(r*cos(a),r*sin(a));
}

complex sqrt(const complex& val)
{
double r=std::sqrt(val.abs()),a=val.arg()/2;
return complex(r*cos(a),r*sin(a));
}
#pragma endregion Класс complex определение

Пример работы:
Код:

9+5i -3+7i 5+3i 4-3i -9+6i -7-3i -8-1i 3+9i
8-4i 2+7i -2+8i -9-2i -8-3i 3-10i -7-9i 9
2-2i -2+5i -1+3i -5-6i 3+4i 6+1i 8+4i -10-8i
-1 4-3i 5-10i 5-9i 4-6i 5+1i -10+9i -6+6i
-7i 9i 5-10i 7-9i 8-7i 8+8i -7i -10-9i
Неизвестный
09.05.2009, 20:19
общий
можно вам вопрос Micren? то есть мне сейчас его попробовать отладить и запустить? и main сделать? Спасибо!!!ЗА помощь, если что можно будет вопросы задавать?..
Неизвестный
09.05.2009, 22:02
общий
Тот main(), который у меня, чисто тестирует конструкторы и все. Сделайте себе как Вам надо.
давно
Мастер-Эксперт
425
4118
11.05.2009, 06:33
общий
Кашапова Аиша Рифгатовна
Вы себе сначала составьте на бумажке, обычными словами, каким должен быть Ваш класс, например:
а) Класс комплексных матриц должен содержать:
1. То-то
2. То-то
3. То-то
б) Класс комплексных матриц должен делать:
1. То-то
2. ТО-то
3. То-то

И сразу станет понятным что делать. По пункту а у Вас будут свойства класса, т.е. какие данные он должен содержать для своей работы, а по пункту б методы класса, т. е. что класс должен делать со своими свойствами.
Об авторе:
Я только в одном глубоко убеждён - не надо иметь убеждений! :)
Неизвестный
11.05.2009, 15:53
общий
Micren,можно вновь обратиться к вам с вопросом ?.. За помощью. преподаватель просит нас создать все не в одном срр, а отдельно пять частей: Complex.h, complex.cpp, matrix.h, matrix.cpp
стала реализовывать так, но возникли ошибки. помогите пожалуйста создать именно в таком формате... ...Пожалуйста!

Код:
//Complex.h


#ifndef COMPLEX_H
#define COMPLEX_H

//#pragma region Класс complex декларация
class matrix;
class complex
{
private:
double _re;
double _im;

public:
// Конструктор
complex(double re=0, double im=0);
// Оператор ()
complex& operator()(double re=0, double im=0);
complex& operator()(const complex& val);
// Оператор "равно"
bool operator==(const complex& val) const;
// Оператор "не равно"
bool operator!=(const complex& val) const;
// Возвращает действительную часть
double re(void) const;
static double re(const complex& val);
// Возвращает мнимую часть
double im(void) const;
static double im(const complex& val);
// Выделение модуля
double abs(void) const;
static double abs(const complex& val);
// Аргумент
double arg(void) const;
static double arg(const complex& val);
// Оператор сложения
complex operator+(const complex& val1,const complex& val2);
complex& operator+=(const complex& val);
// Оператор вычитания
complex operator-(const complex& val1,const complex& val2);
complex& operator-=(const complex& val);
// Оператор умножения
complex operator*(const complex& val1,const complex& val2);
complex& operator*=(const complex& val);
// Опрератор деления
complex operator/(const complex& val1,const complex& val2);
complex& operator/=(const complex& val);
// Возведение в степень
complex pow(const complex& val,double deg);
// Извлечение квадратного корня
complex sqrt(const complex& val);
// Операторы ввода/вывода
//ostream& operator<<(ostream& stream,const complex& val);
//stream& operator>>(istream& stream,complex& val);

};
//#pragma endregion
#endif



//Complex.cpp

#include <stdio.h>
#include <iostream>
#include <math.h>
#include "Complex.h"
#include "Matrix.h"
using namespace std;

//#pragma region Класс complex определение
// Конструктор
inline complex::complex(double re, double im)
: _re(re), _im(im)
{
}

inline complex& complex::operator()(double re, double im)
{
_re=re;
_im=im;
return *this;
}
inline complex& complex::operator ()(const complex& val)
{
_re=val._re;
_im=val._im;
return *this;
}

ostream& operator<<(ostream& stream,const complex& val)
{
if(val._re||!val._im)stream<<val._re;
if(val._im)
{
ios_base::fmtflags flags=stream.flags();
if(val._re)stream.setf(ios::showpos);
stream<<val._im<<'i';
stream.flags(flags);
}
return stream;
};

istream& operator>>(istream& stream,complex& val)
{
double re,im;
stream>>re>>im;
if(stream.good())
{
val._re=re;
val._im=im;
}
return stream;
};
inline bool complex::operator==(const complex& val) const
{
return (_re==val._re)&&(_im==val._im);
}

inline bool complex::operator!=(const complex& val) const
{
return (_re!=val._re)||(_im!=val._im);
}

// Возвращает действительную часть
inline double complex::re(void) const
{
return _re;
}
inline double complex::re(const complex& val)
{
return val._re;
}

// Возвращает мнимую часть
inline double complex::im(void) const
{
return _im;
}
inline double complex::im(const complex& val)
{
return val._im;
}

// Оператор сложения
inline complex operator+(const complex& val1,const complex& val2)
{
return complex(val1._re+val2._re,val1._im+val2._im);
}
inline complex& complex::operator+=(const complex& val)
{
_re+=val._re;
_im+=val._im;
return *this;
}

// Оператор вычитания
inline complex operator-(const complex& val1,const complex& val2)
{
return complex(val1._re-val2._re,val1._im-val2._im);
}
inline complex& complex::operator-=(const complex& val)
{
_re-=val._re;
_im-=val._im;
return *this;
}

// Оператор умножения
complex operator*(const complex& val1,const complex& val2)
{
return complex(val1._re*val2._re-val1._im*val2._im,val1._re*val2._im+val1._im*val2._re);
}
complex& complex::operator*=(const complex& val)
{
_re=_re*val._re-_im*val._im;
_im=_re*val._im+_im*val._re;
return *this;
}

// Опрератор деления
complex operator/(const complex& val1,const complex& val2)
{
double div=val2._re*val2._re+val2._im*val2._im;
return complex((val1._re*val2._re+val1._im*val2._im)/div,(val1._im*val2._re-val1._re*val2._im)/div);
}
complex& complex::operator/=(const complex& val)
{
double div=val._re*val._re+val._im*val._im;
_re=(_re*val._re+_im*val._im)/div;
_im=(_im*val._re-_re*val._im)/div;
return *this;
}

// Выделение модуля
inline double complex::abs(void) const
{
return std::sqrt(_re*_re+_im*_im);
}
inline double complex::abs(const complex& val)
{
return std::sqrt(val._re*val._re+val._im*val._im);
}

// Аргумент
inline double complex::arg(void) const
{
return acos(_re/abs());
}
inline double complex::arg(const complex& val)
{
return acos(val._re/val.abs());
}

complex pow(const complex& val,double deg)
{
double r=std::pow(val.abs(),deg),a=val.arg()*deg;
return complex(r*cos(a),r*sin(a));
}

complex sqrt(const complex& val)
{
double r=std::sqrt(val.abs()),a=val.arg()/2;
return complex(r*cos(a),r*sin(a));
}
//#pragma endregion Класс complex определение



//Matrix.h

#ifndef MATRIX_H
#define MATRIX_H

//#pragma region class matrix
template<class T>
class matrix
{
public:
class _row
{
public:
T& operator[](unsigned int col);
private:
_row(unsigned int cols);
_row(const typename matrix<T>::_row& r);
_row& operator=(const typename matrix<T>::_row& r);
virtual ~_row();
T* _data;
unsigned int _cols;
friend class matrix;
}
_row** _data;
unsigned int _rows,_cols;
public:
// Конструктор создающий матрицу с rows-строками и cols-колонками
matrix(unsigned int rows,unsigned int cols);
// Конструктор копирования
matrix(const matrix<T>& matr);
// Оператор присваивания
matrix<T>& operator=(const matrix<T>& matr);
// Деструктор
virtual ~matrix();
_row& operator[](unsigned int row);
// Возвращает количество строк
unsigned int rows() const;
// Возвращает количество колонок
unsigned int cols() const;
};
//#pragma endregion class matrix
#endif


//Matrix.cpp

#include <iostream>
#include <math.h>
#include <stdio.h>
#include <iomanip>
#include <string.h>
#include "Matrix.h"
#include "Complex.h"
using namespace std;

//#pragma region Класс matrix определение
template<class T>
matrix<T>::matrix(unsigned int rows, unsigned int cols)
:_rows(rows)
,_cols(cols)
,_data(0)
{
_data=new _row*[_rows];
for(unsigned int i=0;i<_rows;++i)
{
_data[i]=new _row(_cols);
}
}

template<class T>
matrix<T>::matrix( const matrix<T>& matr )
:_rows(matr._rows)
,_cols(matr._cols)
,_data(0)
{
_data=new _row*[_rows];
for(unsigned int i=0;i<_rows;++i)
{
_data[i]=new _row(_cols);
*(_data[i])=*(matr._data[i]);
}
}

template<class T>
matrix<T>& matrix<T>::operator=( const matrix<T>& matr )
{
if(&matr!=this)
{
if(_data)
{
for(unsigned int i=0;i<_rows;++i)
{
delete _data[i];
}
delete []_data;
}
_rows=matr._rows;
_cols=matr._cols;
_data=new _row*[_rows];
for(unsigned int i=0;i<_rows;++i)
{
_data[i]=new _row(_cols);
*_data[i]=*matr._data[i];
}
}
return *this;
}

template<class T>
matrix<T>::~matrix()
{
if(_data)
{
for(unsigned int i=0;i<_rows;++i)
{
if(_data[i])delete _data[i];
}
delete []_data;
}
}

template<class T>
typename matrix<T>::_row& matrix<T>::operator[](unsigned int row)
{
if(row<_rows)return *_data[row];
else throw range_error("Bound(row) out of range");
}

template<class T>
inline unsigned int matrix<T>::cols() const
{
return _cols;
}

template<class T>
inline unsigned int matrix<T>::rows() const
{
return _rows;
}


template<class T>
matrix<T>::_row::~_row()
{
if(_data)delete []_data;
}

template<class T>
typename matrix<T>::_row& matrix<T>::_row::operator=(const typename matrix<T>::_row& r )
{
if(&r!=this)
{
if(_data)delete []_data;
_cols=r._cols;
_data=new T[_cols];
for(unsigned int i=0;i<_cols;++i)
{
_data[i]=r._data[i];
}
}
return *this;
}

template<class T>
matrix<T>::_row::_row(const typename matrix<T>::_row& r )
:_cols(r._cols)
,_data(0)
{
_data=new T[_cols];
for(unsigned int i=0;i<_cols;++i)
{
_data[i]=r._data[i];
}
}

template<class T>
matrix<T>::_row::_row( unsigned int cols )
:_cols(cols)
,_data(0)
{
_data=new T[cols];
}

template<class T>
T& matrix<T>::_row::operator [](unsigned int col)
{
if(col<_cols)return _data[col];
else throw range_error("Bound(col) out of range");
}
//#pragma endregion Класс matrix определение




//main.cpp


#include <locale>
#include <valarray>
#include <ios>
#include <iostream>
#include <iomanip>
#include <exception>
#include <ctime>
#include <cstdlib>


#include "Matrix.h"
using namespace std;



int main()
{
srand(static_cast<unsigned int>(time(0)));
const unsigned int ROWS=5,COLS=8;
matrix<complex> arr(ROWS,COLS);
for(unsigned int i=0;i<arr.rows();++i)
{
for(unsigned int j=0;j<arr.cols();++j)
{
arr[i][j]=complex(rnd(20)-10,rnd(20)-10);
}
}
matrix<complex> arr2(arr);
arr=arr2;
for(unsigned int i=0;i<arr.rows();++i)
{
for(unsigned int j=0;j<arr.cols();++j)
{
cout<<arr[i][j]<<' ';
}
cout<<endl;
}
system("PAUSE");
return 0;
}
Неизвестный
11.05.2009, 17:28
общий
Проект под MS VS 2008
http://rusfaq.ru/upload/1691
Неизвестный
11.05.2009, 18:23
общий
Благодарю!! Почему вы перегружали операторы(+,- и прочее) я двумя параметрами? Преподаватель меня просит убрать один параметр..Говорит, что операторы перегружаются с одним. Подскажите пожалуйста? Спасибо вам за помощь, очень грамотно пишите
Неизвестный
11.05.2009, 18:35
общий
Подскажте пожалуйста, можно ли не сипользовать friend? Она также смущает моего преподавателя, и он просил ее убрать.. Требует так, как хочет он, это и справедливо.. Еще там есть класс row, скажите пожалуйста, для чего он нужен и можно ли без него? Иначе я не сумею ответить, что это такое...
Неизвестный
11.05.2009, 22:22
общий
Ваш преподаватель не прав. Если Вы перегрузите бинарные операторы так как хочет того преподаватель, то не сможете использовать эти операторы для операций типа:
double op complex. Вам придется либо явно преобразовывать double в complex(что в моем случае делается автоматически благодаря неявному преобразованию через конструктор), либо написать бинарный оператор опять таки с двумя параметрами для этого(чего в моем случае делать не надо).
Класс complex разрабатывался для задания http://rusfaq.ru/info/question/159929. Там же подробно тестируются и операции с ним.

В общем это тонкости, о которых Ваш преподаватель, видимо, не подозревает. Дружественные(friend) функции и классы это часть синтаксиса языка и может быть изменить стандарт по прихоти Вашего препода?

Класс _row в данном случае это строка матрицы. В будущем можно легко нарастить функционал для операций не только с отдельными элементами матрицы, но и с ее строками. Без него можно, но это не даст никаких перспектив.
Неизвестный
11.05.2009, 22:44
общий
Насчет row- как же можно изменить их под другой тип?сделать не классом, а чем-то другим. ДА, я согласна, преподавател хочет все так, как он делал. Он друженственные не сипользовал, вот он и просил их убрать. Просит именно так, а не иначе. могу программу его прислать. он просит копию такую:) это уже не стол важно. Можно вас будет попросить об одном,пожалуйста? Нам в отчете нужно до распечатки самой программы и решения(скриншота черного экрана) нужно еще до этого написать все методы и функции,которые мы использвоали в программе. Я не знаю все ваши функции, для чего их использовали.можно будет чуть позже я напишу все йункции, а рядом, где я не сомгла ответ найти или гед не верен ответ, вы подскажете?
Неизвестный
11.05.2009, 22:57
общий
Все функции там где объявлены имеют краткий комментарий о их назначении. Если Вам что-либо не понятно конкретно, то напишите отвечу. И чем Вас _row то смущает? Попробуйте написать по другому индексатор (operator[]()) для класса matrix. Кроме того такая реализация в дальнейшем дает перспективу строить такие специфические массивы как зубчатые, возможность вставки/удаления строк и т.п. вещи. Конечно для этого надо немного добавить функционал, но перспективы явные.
Неизвестный
11.05.2009, 23:05
общий
я думаю,что преподаватель спросит, зачем я создала еще один класс row;на это я не смогу ответить , переправить..
Неизвестный
11.05.2009, 23:07
общий
Класс _row это строка матрицы вот и все. Что там отвечать то? В самом классе matrix хранятся не элементы, а указатели на строки _row.
давно
Мастер-Эксперт
425
4118
12.05.2009, 04:55
общий
Кашапова Аиша Рифгатовна
Класс может содержать внутри себя как элементарные типы данных, например, int, double, char*, так и сложные, классы к примеру.
Для чего нужны другие классы внутри классов? Если класс содержит матрицу (или двумерный массив), то в этом классе необходимо описать все методы, которые нужны для работы с матрицей (или массивом). Если же часть подобных методов есть в другом классе, который тем или иным образом может быть частью главного класса, то вместо того, чтобы делать дурную работу, по второму разу описывая методы которые уже есть, лучше включить тот класс в состав главного класса и съэкономить кучу времени при создании главного класса.
Как Вам уже совершенно справедливо сказал эксперт Micren, класс никогда не создаётся только для сиюминутной потребности. Класс создаётся для работы на перспективу, т.е. с возможностью дальнейшего наращивания его функционала. Таким образом мы, в свою очередь, экономим часть времени будущему разработчику.
Об авторе:
Я только в одном глубоко убеждён - не надо иметь убеждений! :)
Неизвестный
12.05.2009, 10:31
общий
благодарю за подробное объяснение, sir Henry!
Форма ответа