Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/5: Рейтинг темы: голосов - 5, средняя оценка - 4.80
1 / 1 / 0
Регистрация: 30.04.2012
Сообщений: 7
1

Приведение типов.

30.04.2012, 12:05. Показов 886. Ответов 9
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Доброго времени суток!

В общем, есть класс Matrix(прямоугольные над полем вещ. чисел). Необходимо реализовать приведение типов Matrix -> double и double -> Matrix. Значит, как я пытаюсь это сделать:
C++
1
2
3
4
5
6
7
8
9
10
class Matrix{
private:
double** data;
//..
public:
//...
Matrix& operator =(double a);
Matrix(double a); // Значит, так привожу double к Matrix. Это вроде работает.
operator double(); // Matrix->double. Тоже работает, но пытается привести где ни поподя.
}
Реализация operator double():
C++
1
2
3
4
5
6
Matrix::operator double()
{
if(m!=1 || n!=1)//m и n количество строк и столбцов соответственно.
throw cantConv();
return data[0][0];
}
Проблема следующая:
Когда какая-либо функция возвращает значиние типа Matrix, почему-то срабатывает operator double(). Например:
C++
1
2
3
4
5
6
7
Matrix Matrix::operator + (Matrix& const A)
{
//...
Matrix result;
//...
return result;// Вот тут пытается привести и, что логично, вылетает исключение типа cantConv(т.к. размерность больше 1).
}
Буду благодарен за помощь.

Добавлено через 20 минут
Ах да, вызов operator+ происходит следующим образом:
C++
1
2
Matrix A(2,2), B(2,2), C;
C = A+B;
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
30.04.2012, 12:05
Ответы с готовыми решениями:

Приведение типов
Как компилятор заставить адекватней приводить типы? (VS2012) Например: int a=-1; unsigned int...

Приведение типов
При вводе с клавиатуры s = 11 и a = 1.1, получаем 9. Результат переменной d = 10, это правильно. В...

Приведение типов
Всем привет) Есть массив int a = {2 ,4 ,5 ,6 ,256} Числа располагаются по байтам в памяти так:...

Приведение типов
Есть задача создать список с объектами у которых разные классы, но один базовый предок. Потом...

9
Эксперт С++
2381 / 1665 / 279
Регистрация: 29.05.2011
Сообщений: 3,399
30.04.2012, 12:12 2
Оператор присваивания от матрицы (Matrix = Matrix) определён? И конструктор копирования тоже бы неплохо иметь.
1
1 / 1 / 0
Регистрация: 30.04.2012
Сообщений: 7
30.04.2012, 12:20  [ТС] 3
Да, оператор присваивания и конструктор копирования определены и работают как часы, если закомментировать определение operator double().

Добавлено через 5 минут
Хотя, простите... я не правильно указал место вылета исключения:
На самом деле так:
C++
1
2
3
4
5
6
7
8
Matrix& Matrix::operator=(Matrix& const A)
{
    getMemory(A.m, A.n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            data[i][j] = A.data[i][j];
    return *this; // Вот тут вылетает
}
0
программист С++
860 / 600 / 147
Регистрация: 19.12.2010
Сообщений: 2,014
30.04.2012, 12:29 4
GeneMeister, хорош уже кусками выкладывать
давай весь код
1
1 / 1 / 0
Регистрация: 30.04.2012
Сообщений: 7
30.04.2012, 12:48  [ТС] 5
Matrix.h:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#ifndef Matrix_h__
#define Matrix_h__
#include <iostream>
#include <exception>
using namespace std;
 
class badDim:public exception
{
    virtual const char* what() const throw();
};
class notConv:public exception
{
    virtual const char* what() const throw();
};
class Matrix 
{
protected:
    double** data;
    int m;
    int n;
    void destruct();
public:
    void getMemory(int _m, int _n);
    Matrix();
    Matrix(int m, int n);
    Matrix& operator =(Matrix& const A);
    Matrix& operator =(double a);
    Matrix(Matrix& const A);
    Matrix(double a);
    ~Matrix();
    int getn();
    int getm();
    double* operator[](int i);
    Matrix operator +(Matrix& const A);
    operator double();
};
istream& operator >> (istream& in,Matrix& A);
ostream& operator << (ostream& out,Matrix& const A);
#endif
Matrix.cpp:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include <cstddef>
#include "Matrix.h"
#include <cmath>
#define eps 1e-6
 
void Matrix::destruct()
{
    for (int i = 0; i < m; i++)
    {
        delete [] data[i];
    }
    delete [] data;
    data = NULL;
}
void Matrix::getMemory(int _m, int _n)
{
    if (data == NULL)
    {
        data = new double*[_m];
        for (int i = 0; i < _m; i++)
        {
            data[i] = new double[_n];
        }
        m = _m;
        n = _n;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                data[i][j] = 0;
    }
    else
    {
        destruct();
        getMemory(_m, _n);
    }
}
Matrix::Matrix()
{
    data = NULL;
    getMemory(1, 1);
    data[0][0] = 0;
}
Matrix::Matrix(int _m, int _n)
{
    data = NULL;
    getMemory(_m, _n);
}
Matrix& Matrix::operator=(Matrix& const A)
{
    getMemory(A.m, A.n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            data[i][j] = A.data[i][j];
    return *this;
}
Matrix& Matrix::operator=(double a)
{
    getMemory(1,1);
    data[0][0] = a;
    return *this;
}
Matrix::Matrix(Matrix& const A)
{
    data = NULL;
    *this = A;  
}
Matrix::Matrix(double a)
{
    data = NULL;
    getMemory(1, 1);
    *this = a;
}
Matrix::~Matrix()
{
    destruct();
}
 
int Matrix::getn()
{
    return n;
}
int Matrix::getm()
{
    return m;
}
ostream& operator << (ostream& out,Matrix& const A)
{
    int n = A.getn(), m = A.getm();
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
            out << A[i][j] << '\t';
        out << '\n';
    }
    return out;
}
Matrix Matrix::operator +(Matrix& const A)
{
    if (m != A.m || n != A.n)
        throw badDim();
    Matrix result(m, n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
        {
            result[i][j] = data[i][j]+A[i][j];
        }
    return result;
}
 
istream& operator >> (istream& in, Matrix& A)
{
    int k = 0;
    while (in.good())
    {
        double d;
        in >> d;
        k++;
    }
    in.clear();
    in.seekg(ios::beg);
    int m = 0;
    while (in.good())
    {
        char buf[256];
        in.getline(buf, 255);
        m++;
    }
    int n = k/m;
    in.clear();
    in.seekg(ios::beg);
    A.getMemory(m,n);
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            in>>A[i][j];
    return in;
}
double* Matrix::operator[](int i)
{
    return data[i];
}
Matrix::operator double()
{
    if(m != 1 || n != 1)
        throw notConv();
    return data[0][0];
}
const char* badDim::what() const throw()
{
    return "Operands have incompatible dimensions.";
}
const char* notConv::what() const throw()
{
    return "Can't convert Matrix to double.";
}
main.cpp:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "Matrix.h"
int main()
{
    Matrix A(2,2), B(2,2), C;
    try
    {
        C=A+B;
        cout << C;
        return 0;
    }
    catch(exception& e)
    {
        cerr << e.what();
        return 1;
    }   
}
0
программист С++
860 / 600 / 147
Регистрация: 19.12.2010
Сообщений: 2,014
30.04.2012, 12:59 6
C++
1
Matrix& const A
это не конструктор копирования
пиши
C++
1
Matrix const& A
или
C++
1
const Matrix& A
1
Эксперт С++
2381 / 1665 / 279
Регистрация: 29.05.2011
Сообщений: 3,399
30.04.2012, 13:11 7
Поправил консты. У меня компилируется и запускается. Выводит 4 нуля.
Matrix.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#ifndef Matrix_h__
#define Matrix_h__
#include <iostream>
#include <exception>
using namespace std;
 
class badDim:public exception
{
    virtual const char* what() const throw();
};
class notConv:public exception
{
    virtual const char* what() const throw();
};
class Matrix 
{
protected:
    double** data;
    int m;
    int n;
    void destruct();
public:
    void getMemory(int _m, int _n);
    Matrix();
    Matrix(int m, int n);
    Matrix& operator =(Matrix const& A);
    Matrix& operator =(double a);
    Matrix(Matrix const& A);
    Matrix(double a);
    ~Matrix();
    int getn() const;
    int getm() const;
    double* operator[](int i);
    double const* operator[](int i) const;
    Matrix operator +(Matrix const& A);
    operator double();
};
istream& operator >> (istream& in,Matrix& A);
ostream& operator << (ostream& out,Matrix const& A);
#endif
Matrx.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <cstddef>
#include "Matrix.h"
#include <cmath>
#define eps 1e-6
 
void Matrix::destruct()
{
    for (int i = 0; i < m; i++)
    {
        delete [] data[i];
    }
    delete [] data;
    data = NULL;
}
void Matrix::getMemory(int _m, int _n)
{
    if (data == NULL)
    {
        data = new double*[_m];
        for (int i = 0; i < _m; i++)
        {
            data[i] = new double[_n];
        }
        m = _m;
        n = _n;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                data[i][j] = 0;
    }
    else
    {
        destruct();
        getMemory(_m, _n);
    }
}
Matrix::Matrix()
{
    data = NULL;
    getMemory(1, 1);
    data[0][0] = 0;
}
Matrix::Matrix(int _m, int _n)
{
    data = NULL;
    getMemory(_m, _n);
}
Matrix& Matrix::operator=(Matrix const& A)
{
    getMemory(A.m, A.n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            data[i][j] = A.data[i][j];
    return *this;
}
Matrix& Matrix::operator=(double a)
{
    getMemory(1,1);
    data[0][0] = a;
    return *this;
}
Matrix::Matrix(Matrix const& A)
{
    data = NULL;
    *this = A;  
}
Matrix::Matrix(double a)
{
    data = NULL;
    getMemory(1, 1);
    *this = a;
}
Matrix::~Matrix()
{
    destruct();
}
 
int Matrix::getn() const
{
    return n;
}
int Matrix::getm() const
{
    return m;
}
ostream& operator << (ostream& out,Matrix const& A)
{
    int n = A.getn(), m = A.getm();
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
            out << A[i][j] << '\t';
        out << '\n';
    }
    return out;
}
Matrix Matrix::operator +(Matrix const& A)
{
    if (m != A.m || n != A.n)
        throw badDim();
    Matrix result(m, n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
        {
            result[i][j] = data[i][j]+A[i][j];
        }
    return result;
}
 
istream& operator >> (istream& in, Matrix& A)
{
    int k = 0;
    while (in.good())
    {
        double d;
        in >> d;
        k++;
    }
    in.clear();
    in.seekg(ios::beg);
    int m = 0;
    while (in.good())
    {
        char buf[256];
        in.getline(buf, 255);
        m++;
    }
    int n = k/m;
    in.clear();
    in.seekg(ios::beg);
    A.getMemory(m,n);
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            in>>A[i][j];
    return in;
}
double* Matrix::operator[](int i)
{
    return data[i];
}
double const* Matrix::operator[](int i) const
{
    return data[i];
}
Matrix::operator double()
{
    if(m != 1 || n != 1)
        throw notConv();
    return data[0][0];
}
const char* badDim::what() const throw()
{
    return "Operands have incompatible dimensions.";
}
const char* notConv::what() const throw()
{
    return "Can't convert Matrix to double.";
}
1
1 / 1 / 0
Регистрация: 30.04.2012
Сообщений: 7
30.04.2012, 13:15  [ТС] 8
Спасибо всем большое!
0
программист С++
860 / 600 / 147
Регистрация: 19.12.2010
Сообщений: 2,014
30.04.2012, 13:15 9
Цитата Сообщение от grizlik78 Посмотреть сообщение
Поправил консты. У меня компилируется и запускается. Выводит 4 нуля.
ну собственно это программа и должна выводить)
1
Эксперт С++
2381 / 1665 / 279
Регистрация: 29.05.2011
Сообщений: 3,399
30.04.2012, 13:21 10
Цитата Сообщение от sandye51 Посмотреть сообщение
ну собственно это программа и должна выводить)
Я знаю
0
30.04.2012, 13:21
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
30.04.2012, 13:21
Помогаю со студенческими работами здесь

Приведение типов.
Столкнулся с задачей считывания данных из символьного массива с дальнейшим отбором из всего этого...

Приведение типов
Доброго времени суток. Данный кусок кода выделяет целую часть. Потом, вычитая из исходного числа...

приведение типов
Объясните, пожалуйста, почему возникает такая ошибка: error C2666: 'operator *' : 4 overloads have...

Приведение типов
Делаю программу, которая кроме всего прочего должна отсортировать массив. Использую для этого...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru