Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.75/4: Рейтинг темы: голосов - 4, средняя оценка - 4.75
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1

Template. Numerical Array

19.06.2012, 14:30. Показов 941. Ответов 12
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
I what to implement to my Template operator * .
So, Very simple idea.
There is <Template> Array which purpose is container like vector for classes
There is class Point, each object of contain two coordinate x and y.
So,
1. I wanna fill Array with objects from Point class
2. Multiply each objects from this vector to a factor
3. And print all this bunch of objects ()...

Я хочу нормально перегрузить оператор *
Очень простая идея.
Есть тимплейт ARRAY который работает как контейнер типа как вектор.
Есть Класс Point, каждый объект которого состоит из двух координат
Короче
1. Я хочу заполнить Array объектами класса Point
2. Умножить каждый объект из этого вектора на число
3. Распечатать все это

Compile error :
1>------ Build started: Project: HP_4.2b_Ex2, Configuration: Release Win32 ------
1> main.cpp
1>main.cpp(21): error C2440: 'initializing' : cannot convert from 'Point' to 'Array<Type>'
1> with
1> [
1> Type=Point
1> ]
1> No constructor could take the source type, or constructor overload resolution was ambiguous
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

code :
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
158
159
160
161
162
163
164
165
166
167
//array.h
#ifndef Array_H
#define Array_H
 
template <class Type> //Remove the "=double" default parameter.
class Array
{
protected:
  int m_size;
  Type* m_data; //m_data should be a pointer, since you want to allocate data to it
 
public:
  Array();
  Array(int new_size);
  Array(const Array<Type>& ar);
  ~Array(); //Don't make your destructor virtual. There is no reason to do it.
  Type& operator * (double factor) const;
  Type& operator [] (int index);
  int Size() const;
  void Swap(Array& ar);  
};
 
 
 
#endif
 
//************
//************
 
//point.h
 
#include "array.h"
#include <sstream>
#include <iostream>
using namespace std;
 
 
class Point
{
private:
    double m_x;                                
    double m_y;                                
public:
    // Constructors
    Point(): m_x(0), m_y(0) {};                            
    Point(double new_x, double new_y) : m_x(new_x), m_y(new_y) {};
    friend ostream& operator << (ostream& os, const Point& point)
{
    return os << point.ToString();
}
    std::string Point::ToString(void) const                // create a string representation of a point
{
// create a string like: “Point(1.5, 3.9)”
      std::ostringstream os;
    os << m_x << " , " << m_y;
    std::string double_string = os.str();
 
    return "Point(" + double_string + ")";
}
};
 
//************
//************
//************
//************
 
//array.cpp
#include "Array.h"
#include <sstream>
#include <iostream>
#include <exception>
using namespace std;
#ifndef Array_CPP
#define Array_CPP
 
 
template <class Type>
Array<Type>::Array() : m_size(10), m_data(0) 
{
}
template <class Type>
Array<Type>::Array(int new_size) : m_size(new_size), m_data(new Type[new_size])
{ 
}
 
template <class Type>
Array<Type>::~Array()
{
  //Technically, the if is not necessary
  if(m_data)
  {
    delete[] m_data;
    m_data = 0;
  }
 
  //Not necessary either, but just to be clean
  m_size = 0;
}
 
 
template <class Type> 
Type& Array<Type>::operator [] (int index) 
{
    cout << "Array [] operator" << endl;
 
    if (index > this->m_size)
    {
        cout << "i am hreeeee" << endl;
        return this->m_data[0];
    }
    return m_data[index];
}
template<class Type>
int Array<Type>::Size() const
{
    return this->m_size; 
}
 
template<class Type>
Type& Array<Type>::operator * (double factor) const
{
Array<Type> output(Array<Type>::Size());
for(int i=0; i<Array::Size(); i++)
    {
output[i] = Array<T>::operator[](i) * factor;
    }
return output;
}
 
 
#endif //Array_CPP
 
//************
//************
//************
//************
 
//main.cpp
        #include "point.h"
        
        #include <iostream>
        #include "array.cpp"
        using namespace std;
 
int main()
{
              //Create two Point arrays and test the operators
    Array<Point> pArray1(5);
    Array<Point> pArray2(5);
    //initialize
    for(int i=0; i<pArray1.Size(); i++) pArray1[i] = Point(i, i);
    for(int i=0; i<pArray2.Size(); i++) pArray2[i] = Point(2*i, 2*i);
 
    //Numeric Array's operations not working for Point objects
 
 
    cout << "times PointArray1 by 3 and print out the new array: "<< endl;
    Array<Point> answ1 = pArray1 * 3;
    
    for(int i=0; i<answ1.Size(); i++){
        cout << answ1[i] << endl;
 
    }
 
 
    
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
19.06.2012, 14:30
Ответы с готовыми решениями:

Ошибки: 1) use of class template requires template argument list 2) 'T' : undeclared identifier
Решил подправить свой класс с использованием шаблонов, но столкнулся со следующим косяком. Если я прописываю тело функций внутри описания...

Template definition of non-template при использовании частичной спецификации шаблонов
Всем привет! Есть задача написать шаблон класса, принимающего в качестве параметров типа шаблон и некоторый тип. Собственно, вот код: ...

'MyQueue' : use of class template requires template argument list
Написал код про шаблоны. Не могу понять почему выводит ошибку во время наследования класса. ошибки 'MyQueue' : use of class template...

12
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
19.06.2012, 14:40
Цитата Сообщение от Leeto Посмотреть сообщение
Type& Array<Type>::operator * (double factor) const
Тип возвращаемого значения не тот.
C++
1
Array<Type> Array<Type>::operator * (double factor) const
Добавлено через 56 секунд
Цитата Сообщение от Leeto Посмотреть сообщение
Array<T>::operator[](i)
можно заменить на
C++
1
(*this)[i]
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
19.06.2012, 14:45  [ТС]
Цитата Сообщение от gray_fox Посмотреть сообщение
Тип возвращаемого значения не тот.
C++
1
Array<Type> Array<Type>::operator * (double factor) const
Добавлено через 56 секунд

можно заменить на
C++
1
(*this)[i]
не понЯл поясни плиз

Добавлено через 3 минуты
Спасибо большое но компилятор продолжает ту же ошибку выдовать
0
 Аватар для Gepar
1186 / 543 / 78
Регистрация: 01.07.2009
Сообщений: 3,517
19.06.2012, 14:46

Не по теме:

Цитата Сообщение от Leeto Посмотреть сообщение
I what to implement to my Template operator * .
!=
Цитата Сообщение от Leeto Посмотреть сообщение
Я хочу нормально перегрузить оператор *


.....
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
19.06.2012, 14:48  [ТС]
Цитата Сообщение от Gepar Посмотреть сообщение

Не по теме:


!=


.....
не согласен )
0
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
19.06.2012, 14:49
Цитата Сообщение от Leeto Посмотреть сообщение
не понЯл поясни плиз
Извини, но я не понял, что ты не понял) про operator * или [] ?
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
19.06.2012, 14:52  [ТС]
Цитата Сообщение от gray_fox Посмотреть сообщение
Извини, но я не понял, что ты не понял) про operator * или [] ?
ненен все ща ок... ты потом добавил про *this... Я к тому что компилятор продолжает туже ошибку выдавать
0
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
19.06.2012, 15:04
Цитата Сообщение от Leeto Посмотреть сообщение
компилятор продолжает туже ошибку выдават
main.cpp(21): error C2440: 'initializing' : cannot convert from 'Point' to 'Array<Type>'
Я так понимаю 21 строка эта:
C++
1
 Array<Point> answ1 = pArray1 * 3;
Если так и operator * возвращает Array<Type>, то всё должно быть нормально, по крайней мере в этом месте. Кстати, в Array стоит добавить operator = .

Добавлено через 1 минуту
В header то поменял объявление operator * ?

Добавлено через 3 минуты
Ну т.е. в array.h
C++
1
2
3
4
5
6
7
template<class Type>
class Array {
   // ...
public:
   Array operator *(double factor) const;
   // ...
};
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
19.06.2012, 15:08  [ТС]
[QUOTE=gray_fox;3184233]Я так понимаю 21 строка эта:
C++
1
 Array<Point> answ1 = pArray1 * 3;
Если так и operator * возвращает Array<Type>, то всё должно быть нормально, по крайней мере в этом месте. Кстати, в Array стоит добавить operator = .

Добавлено через 1 минуту

Цитата Сообщение от gray_fox Посмотреть сообщение
В header то поменял объявление operator * ?
Нет подожди а что там менять, в хедаре ??? там же просто имплементация немного поменялась просто...

C++
1
 Array<Point> answ1 = pArray1 * 3;
Цитата Сообщение от gray_fox Посмотреть сообщение
Если так и operator * возвращает Array<Type>, то всё должно быть нормально, по крайней мере в этом месте.
Короче у меня всплявающая ошибка указателя ругается на pArray1 и выводит след сообщение
Error: no suitable user defined conversion from "Point " to Array<Point> exist

Цитата Сообщение от gray_fox Посмотреть сообщение
Кстати, в Array стоит добавить operator = .
А зачем ??? у меня кстати это уже не первая ошибка я все не догоняю наверное что то... мы же вроде не юзаем оператор =... поясни плиз в трех словах
0
Каратель
Эксперт С++
6610 / 4029 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
19.06.2012, 15:24
Цитата Сообщение от Leeto Посмотреть сообщение
А зачем ??? у меня кстати это уже не первая ошибка я все не догоняю наверное что то... мы же вроде не юзаем оператор =
Правило трех: если в классе явно определен деструктор, то так же следует явно определить конструктор копирования и оператор присваивания

Аналогично: если в классе явно определен оператор присваивания, то так же следует явно определить конструктор копирования и деструктор

Аналогично: если в классе явно определен конструктор копирования, то так же следует явно определить оператор присваивания и деструктор

С новым стандартом это правило ещё и расширяется
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
19.06.2012, 15:48  [ТС]
Цитата Сообщение от Jupiter Посмотреть сообщение
Правило трех: если в классе явно определен деструктор, то так же следует явно определить конструктор копирования и оператор присваивания

Аналогично: если в классе явно определен оператор присваивания, то так же следует явно определить конструктор копирования и деструктор

Аналогично: если в классе явно определен конструктор копирования, то так же следует явно определить оператор присваивания и деструктор

С новым стандартом это правило ещё и расширяется


Ребят таже ошибка осталась((( я конечно посредственный кодер... я не догоняю многого особенно слова о том как нужно правильно делать, пожалуйста помогите кодом... Кто сколько может строчек... очень прошу !
last edition:

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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//array.h
#ifndef Array_H
#define Array_H
 
template <class Type> //Remove the "=double" default parameter.
class Array
{
protected:
  int m_size;
  Type* m_data; //m_data should be a pointer, since you want to allocate data to it
 
public:
  Array();
  Array(int new_size);
  ~Array(); //Don't make your destructor virtual. There is no reason to do it.
  Array<Type>& operator=(const Array& ar); //Const correctness here.
  Type& operator * (double factor) const;
  Type& operator [] (int index);
  const Type& operator [] (int index) const;
  int Size() const;
};
//****************
//****************
//****************
 
 
#endif
 
//point.h
 
#include "array.h"
#include <sstream>
#include <iostream>
using namespace std;
 
 
class Point
{
private:
    double m_x;                                
    double m_y;                                
public:
    // Constructors
    Point(): m_x(0), m_y(0) {};                            
    Point(double new_x, double new_y) : m_x(new_x), m_y(new_y) {};
    friend ostream& operator << (ostream& os, const Point& point)
{
    return os << point.ToString();
}
    std::string Point::ToString(void) const                // create a string representation of a point
{
// create a string like: “Point(1.5, 3.9)”
      std::ostringstream os;
    os << m_x << " , " << m_y;
    std::string double_string = os.str();
 
    return "Point(" + double_string + ")";
 
}
    Point Point::operator * (double factor) const;
    Point& Point::operator *= (double factor); 
};
 
//****************
//****************
//****************
 
//array.cpp
#include "Array.h"
#include <sstream>
#include <iostream>
#include <exception>
using namespace std;
#ifndef Array_CPP
#define Array_CPP
 
 
template <class Type>
Array<Type>::Array() : m_size(10), m_data(0) 
{
}
template <class Type>
Array<Type>::Array(int new_size) : m_size(new_size), m_data(new Type[new_size])
{ 
}
 
template <class Type>
Array<Type>::~Array()
{
  //Technically, the if is not necessary
  if(m_data)
  {
    delete[] m_data;
    m_data = 0;
  }
 
  //Not necessary either, but just to be clean
  m_size = 0;
}
 
 
 
template <class Type>
Array<Type>& Array<Type>::operator=(const Array& ar)
{
  //Check self assign:
  if(this == &ar) {return *this;}
 
  Array<Type> copy(ar); //Create a copy of ar; If this fails, then *this will not be changed, and nothing will leak
 
  //Succeeded creating copy. Now we can put it inside this
  this->Swap(copy); //And then swap the copy into this!
 
  return *this;
}
 
 
 
 
 
template <class Type> 
Type& Array<Type>::operator [] (int index) 
{
    //cout << "Array [] operator" << endl;
 
    if (index > this->m_size)
    {
        cout << "i am hreeeee" << endl;
        return this->m_data[0];
    }
    return m_data[index];
}
 
template <class Type> 
 const Type& Array<Type>::operator [] (int index) const
 {
  //  cout << "Array [] operator" << endl;
 
    if (index > this->m_size)
    {
        cout << "i am hreeeee" << endl;
        return this->m_data[0];
    }
    return m_data[index];
}
 
template<class Type>
int Array<Type>::Size() const
{
    return this->m_size; 
}
 
template<class Type>
Type& Array<Type>::operator * (double factor) const
{
Array<Type> output(Array<Type>::Size());
for(int i=0; i<Array::Size(); i++)
    {
output[i] = (*this)[i] * factor;
return output;
    }
 
}
 
//****************
//****************
//****************
 
#endif //Array_CPP
 
 
#include "array.h"
#include "Point.h"
#include <sstream>
#include <iostream>
using namespace std;
 
Point Point::operator * (double factor) const
{
    return Point(m_x * factor, m_y * factor);
}
 
 
    Point& Point::operator *= (double factor)
    {
    Point tmp = (*this) * factor;
    *this = tmp;
 
    return *this;
    }
//****************
//****************
//****************
 
//main.cpp
        #include "point.h"
        #include <iostream>
        #include "array.cpp"
        using namespace std;
 
int main()
{
              //Create two Point arrays and test the operators
    Array<Point> pArray1(5);
    Array<Point> pArray2(5);
    //initialize
    for(int i=0; i<pArray1.Size(); i++) pArray1[i] = Point(i, i);
    for(int i=0; i<pArray2.Size(); i++) pArray2[i] = Point(2*i, 2*i);
 
    //Numeric Array's operations not working for Point objects
 
 
    cout << "times PointArray1 by 3 and print out the new array: "<< endl;
    Array<Point> answ1 = pArray1 * 3;
    
    for(int i=0; i<answ1.Size(); i++){
        cout << answ1[i] << endl;
 
    }
 
 
    
}
1>------ Build started: Project: HP_4.2b_Ex2, Configuration: Release Win32 ------
1> Array.cpp
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

1>------ Build started: Project: HP_4.2b_Ex2, Configuration: Release Win32 ------
1> Point.cpp
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========


1>------ Build started: Project: HP_4.2b_Ex2, Configuration: Release Win32 ------
1> main.cpp
1>main.cpp(20): error C2440: 'initializing' : cannot convert from 'Point' to 'Array<Type>'
1> with
1> [
1> Type=Point
1> ]
1> No constructor could take the source type, or constructor overload resolution was ambiguous
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Добавлено через 9 минут
Цитата Сообщение от Jupiter Посмотреть сообщение
Правило трех: если в классе явно определен деструктор, то так же следует явно определить конструктор копирования и оператор присваивания

Аналогично: если в классе явно определен оператор присваивания, то так же следует явно определить конструктор копирования и деструктор

Аналогично: если в классе явно определен конструктор копирования, то так же следует явно определить оператор присваивания и деструктор

С новым стандартом это правило ещё и расширяется
ага т.е. мне еще и копи констрактор надо добавить, а это и для класса и для тимплейта соответственно ? или как ?
0
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
19.06.2012, 15:57
В одном исходнике:
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
template <class Type> //Remove the "=double" default parameter.
class Array
{
protected:
  int m_size;
  Type* m_data; //m_data should be a pointer, since you want to allocate data to it
 
public:
  Array();
  Array(int new_size);
  ~Array(); //Don't make your destructor virtual. There is no reason to do it.
  Array<Type>& operator=(const Array& ar); //Const correctness here.
  //Type& operator * (double factor) const;
  Array operator *(double factor) const;   // я это имел ввиду (про header)
  Type& operator [] (int index);
  const Type& operator [] (int index) const;
  int Size() const;
};
//****************
//****************
//****************
 
#include <sstream>
#include <iostream>
using namespace std;
 
 
class Point
{
private:
    double m_x;                                
    double m_y;                                
public:
    // Constructors
    Point(): m_x(0), m_y(0) {};                            
    Point(double new_x, double new_y) : m_x(new_x), m_y(new_y) {};
    friend ostream& operator << (ostream& os, const Point& point)
{
    return os << point.ToString();
}
    //std::string Point::ToString(void) const                // create a string representation of a point
   string ToString() const
{
// create a string like: “Point(1.5, 3.9)”
      std::ostringstream os;
    os << m_x << " , " << m_y;
    std::string double_string = os.str();
 
    return "Point(" + double_string + ")";
 
}
    //Point Point::operator * (double factor) const;
    Point operator *(double factor) const;   // итак в классе, Point:: не нужно
    //Point& Point::operator *= (double factor); 
    Point & operator *=(double factor);
};
 
//****************
//****************
//****************
 
//array.cpp
//#include "Array.h"
//#include <sstream>
//#include <iostream>
#include <exception>
//using namespace std;
//#ifndef Array_CPP
//#define Array_CPP
 
 
template <class Type>
Array<Type>::Array() : m_size(10), m_data(0) // странно получается, размер 10, а данных нет
{
}
template <class Type>
Array<Type>::Array(int new_size) : m_size(new_size), m_data(new Type[new_size])
{ 
}
 
template <class Type>
Array<Type>::~Array()
{
  //Technically, the if is not necessary
  if(m_data)
  {
    delete[] m_data;
    m_data = 0;
  }
 
  //Not necessary either, but just to be clean
  m_size = 0;
}
 
 
 
template <class Type>
Array<Type>& Array<Type>::operator=(const Array& ar)
{
  //Check self assign:
  if(this == &ar) {return *this;}
 
  Array<Type> copy(ar); //Create a copy of ar; If this fails, then *this will not be changed, and nothing will leak
 
  //Succeeded creating copy. Now we can put it inside this
  this->Swap(copy); //And then swap the copy into this!
 
  return *this;
}
 
 
 
 
 
template <class Type> 
Type& Array<Type>::operator [] (int index) 
{
    //cout << "Array [] operator" << endl;
 
    if (index > this->m_size)
    {
        cout << "i am hreeeee" << endl;
        return this->m_data[0];
    }
    return m_data[index];
}
 
template <class Type> 
 const Type& Array<Type>::operator [] (int index) const
 {
  //  cout << "Array [] operator" << endl;
 
    if (index > this->m_size)
    {
        cout << "i am hreeeee" << endl;
        return this->m_data[0];
    }
    return m_data[index];
}
 
template<class Type>
int Array<Type>::Size() const
{
    return this->m_size; 
}
 
template<class Type>
//Type& Array<Type>::operator * (double factor) const
Array<Type> Array<Type>::operator *(double factor) const
{
   Array<Type> output(Array<Type>::Size());
   for(int i=0; i<Array::Size(); i++)
   {
      output[i] = (*this)[i] * factor;
      //return output;
   }
   return output;
}
 
//****************
//****************
//****************
 
//#endif //Array_CPP
 
 
//#include "array.h"
//#include "Point.h"
//#include <sstream>
//#include <iostream>
//using namespace std;
 
Point Point::operator * (double factor) const
{
    return Point(m_x * factor, m_y * factor);
}
 
 
    Point& Point::operator *= (double factor)
    {
    Point tmp = (*this) * factor;
    *this = tmp;
 
    return *this;
    }
//****************
//****************
//****************
 
//main.cpp
//        #include "point.h"
//        #include <iostream>
//        #include "array.cpp"
//        using namespace std;
 
int main()
{
              //Create two Point arrays and test the operators
    Array<Point> pArray1(5);
    Array<Point> pArray2(5);
    //initialize
    for(int i=0; i<pArray1.Size(); i++) pArray1[i] = Point(i, i);
    for(int i=0; i<pArray2.Size(); i++) pArray2[i] = Point(2*i, 2*i);
 
    //Numeric Array's operations not working for Point objects
 
 
    cout << "times PointArray1 by 3 and print out the new array: "<< endl;
    Array<Point> answ1 = pArray1 * 3;
    
    for(int i=0; i<answ1.Size(); i++){
        cout << answ1[i] << endl;
 
    }
 
 
    
}
http://liveworkspace.org/code/... 89f5653e07
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
19.06.2012, 16:04  [ТС]
Цитата Сообщение от gray_fox Посмотреть сообщение
В одном исходнике:
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
template <class Type> //Remove the "=double" default parameter.
class Array
{
protected:
  int m_size;
  Type* m_data; //m_data should be a pointer, since you want to allocate data to it
 
public:
  Array();
  Array(int new_size);
  ~Array(); //Don't make your destructor virtual. There is no reason to do it.
  Array<Type>& operator=(const Array& ar); //Const correctness here.
  //Type& operator * (double factor) const;
  Array operator *(double factor) const;   // я это имел ввиду (про header)
  Type& operator [] (int index);
  const Type& operator [] (int index) const;
  int Size() const;
};
//****************
//****************
//****************
 
#include <sstream>
#include <iostream>
using namespace std;
 
 
class Point
{
private:
    double m_x;                                
    double m_y;                                
public:
    // Constructors
    Point(): m_x(0), m_y(0) {};                            
    Point(double new_x, double new_y) : m_x(new_x), m_y(new_y) {};
    friend ostream& operator << (ostream& os, const Point& point)
{
    return os << point.ToString();
}
    //std::string Point::ToString(void) const                // create a string representation of a point
   string ToString() const
{
// create a string like: “Point(1.5, 3.9)”
      std::ostringstream os;
    os << m_x << " , " << m_y;
    std::string double_string = os.str();
 
    return "Point(" + double_string + ")";
 
}
    //Point Point::operator * (double factor) const;
    Point operator *(double factor) const;   // итак в классе, Point:: не нужно
    //Point& Point::operator *= (double factor); 
    Point & operator *=(double factor);
};
 
//****************
//****************
//****************
 
//array.cpp
//#include "Array.h"
//#include <sstream>
//#include <iostream>
#include <exception>
//using namespace std;
//#ifndef Array_CPP
//#define Array_CPP
 
 
template <class Type>
Array<Type>::Array() : m_size(10), m_data(0) // странно получается, размер 10, а данных нет
{
}
template <class Type>
Array<Type>::Array(int new_size) : m_size(new_size), m_data(new Type[new_size])
{ 
}
 
template <class Type>
Array<Type>::~Array()
{
  //Technically, the if is not necessary
  if(m_data)
  {
    delete[] m_data;
    m_data = 0;
  }
 
  //Not necessary either, but just to be clean
  m_size = 0;
}
 
 
 
template <class Type>
Array<Type>& Array<Type>::operator=(const Array& ar)
{
  //Check self assign:
  if(this == &ar) {return *this;}
 
  Array<Type> copy(ar); //Create a copy of ar; If this fails, then *this will not be changed, and nothing will leak
 
  //Succeeded creating copy. Now we can put it inside this
  this->Swap(copy); //And then swap the copy into this!
 
  return *this;
}
 
 
 
 
 
template <class Type> 
Type& Array<Type>::operator [] (int index) 
{
    //cout << "Array [] operator" << endl;
 
    if (index > this->m_size)
    {
        cout << "i am hreeeee" << endl;
        return this->m_data[0];
    }
    return m_data[index];
}
 
template <class Type> 
 const Type& Array<Type>::operator [] (int index) const
 {
  //  cout << "Array [] operator" << endl;
 
    if (index > this->m_size)
    {
        cout << "i am hreeeee" << endl;
        return this->m_data[0];
    }
    return m_data[index];
}
 
template<class Type>
int Array<Type>::Size() const
{
    return this->m_size; 
}
 
template<class Type>
//Type& Array<Type>::operator * (double factor) const
Array<Type> Array<Type>::operator *(double factor) const
{
   Array<Type> output(Array<Type>::Size());
   for(int i=0; i<Array::Size(); i++)
   {
      output[i] = (*this)[i] * factor;
      //return output;
   }
   return output;
}
 
//****************
//****************
//****************
 
//#endif //Array_CPP
 
 
//#include "array.h"
//#include "Point.h"
//#include <sstream>
//#include <iostream>
//using namespace std;
 
Point Point::operator * (double factor) const
{
    return Point(m_x * factor, m_y * factor);
}
 
 
    Point& Point::operator *= (double factor)
    {
    Point tmp = (*this) * factor;
    *this = tmp;
 
    return *this;
    }
//****************
//****************
//****************
 
//main.cpp
//        #include "point.h"
//        #include <iostream>
//        #include "array.cpp"
//        using namespace std;
 
int main()
{
              //Create two Point arrays and test the operators
    Array<Point> pArray1(5);
    Array<Point> pArray2(5);
    //initialize
    for(int i=0; i<pArray1.Size(); i++) pArray1[i] = Point(i, i);
    for(int i=0; i<pArray2.Size(); i++) pArray2[i] = Point(2*i, 2*i);
 
    //Numeric Array's operations not working for Point objects
 
 
    cout << "times PointArray1 by 3 and print out the new array: "<< endl;
    Array<Point> answ1 = pArray1 * 3;
    
    for(int i=0; i<answ1.Size(); i++){
        cout << answ1[i] << endl;
 
    }
 
 
    
}
http://liveworkspace.org/code/... 89f5653e07

Круть ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ВАЩЕ ОГРОМНОЕ СПАСИБО !!!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
19.06.2012, 16:04
Помогаю со студенческими работами здесь

В чем различие template <typename T> от template <class T> ?
Добрый день ! Заметил в новых книгах применение записи template &lt;typename T&gt; вместо template &lt;class T&gt; в чем же тогда фишка...

Ошибка компиляции: template-id does not match any template declaration
Здравствуйте. Помогите, пожалуйста: #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; T maxn(T*, const int*); ...

Visual Studio выдаёт ошибку при вынесении объявления функции с template в .h файл. Без template всё работает
Проект содержит три файла: Source.cpp, arrTreat.h, arrTreat.cpp. Source.cpp: #include &lt;iostream&gt; using std::cout; using...

Template Array
std::array&lt;int,4&gt; x = std::array&lt;int,4&gt;(); Disassembly 00EA8570 xor eax,eax 00EA8572 mov dword ptr ,eax ...

Подключение IMSL Fortran Numerical Library 7.0
for


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

Или воспользуйтесь поиском по форуму:
13
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru