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

Возврат vector из класса

17.04.2015, 11:43. Показов 904. Ответов 7
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте.
Из класса ячеек нужно вернуть номера соседних клеток. Думал сделать через вектор. но возникла проблема при создании прототипа метода.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class comb
{
private:
    TCanvas* img;
    int row;
    int col;
    int radius;
    TPoint start;
    cell** g;
public:
        ..................
    int getRow();
    int getCol();
    vector<int> getNeighbors();  // ошибки E2303 Type name expected  и  E2139 Declaration missing ;
//      void (vector<int>& nbrs);     // так тоже не работоает
извините если задал слишком тривиальній вопрос.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
17.04.2015, 11:43
Ответы с готовыми решениями:

Как корректно скопировать vector в vector внутри класса
Есть класс принимающий в конструкторе vector: class test { test(std::vector&lt;std::string&gt;...

Написать шаблон класса на основе класса vector для реализации стековой структуры данных
Пыталась написать код, но не уверена будет ли такая реализация корректной, можно ли это сделать...

Возврат массива из класса
вот класс в котором есть массив а class Population1 { public: Population1(int,int); ...

Инициализация класса, возврат значений
Сама задача: Реализовать класс Rectangle. Класс должен хранить координаты, а так же длину и ширину...

7
Котовчанин
942 / 482 / 200
Регистрация: 16.02.2010
Сообщений: 3,338
Записей в блоге: 37
17.04.2015, 11:45 2
azbest, весь код, пожалуйста.
0
Эксперт С++
2924 / 1274 / 114
Регистрация: 27.05.2008
Сообщений: 3,465
17.04.2015, 11:50 3
C++
1
2
3
4
5
6
7
#include <vector>
 
class ....
{
    std::vector<int> getNeighbors();
 
}
0
42 / 42 / 18
Регистрация: 12.03.2013
Сообщений: 148
17.04.2015, 11:54  [ТС] 4
Пишу на RAD Studio C++ Builder

beecell.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
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
//---------------------------------------------------------------------------
 
#ifndef beecellH
#define beecellH
 
//#include <System.Classes.hpp>
//#include <Vcl.Controls.hpp>
//#include <Vcl.StdCtrls.hpp>
//#include <Vcl.Forms.hpp>
#include <Vcl.ExtCtrls.hpp>
#include <vector>
 
struct pnt
{
    int x;
    int y;
    pnt(): x(0), y(0) {};
    pnt(int _x, int _y): x(_x), y(_y) {}
};
 
class cell
{
private:
    TPoint O;
    int r;
    int borderWidth;
    TColor borderColor;
    TColor fillColor;
    TCanvas* parent;
public:
    cell();
    cell(TCanvas* par, int _x=0, int _y=0 ,int _r=0, TColor bC=clBlack, TColor fC=clWhite, int bW=1);
    void setParent(TCanvas*);
    void setCoord(TPoint);
    void setCoord(int,int);
    void setRadius(int);
    void setBorderColor(TColor);
    void setBorderWidth(int);
    void setFillColor(TColor);
    void draw();
    void ShowText(UnicodeString);
    TPoint pointCoord(int);
};
 
class comb
{
private:
    TCanvas* img;
    int row;
    int col;
    int radius;
    TPoint start;
    cell** g;
public:
    comb(TCanvas* par, int r, int c, TPoint O, int _rad);
    ~comb();
    void paint();
    void draw(int,int);
    void drawColor(int,int,TColor);
    TPoint getCoord(int,int);
    cell& operator()(int,int);
    bool inBounds(int,int);
    bool inBounds(TPoint);
    int getRow();
    int getCol();
    vector<int> getNeighbors();
};
 
//---------------------------------------------------------------------------
#endif
beecell.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
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
//---------------------------------------------------------------------------
#pragma hdrstop
 
#include "beecell.h"
//---------------------------------------------------------------------------
 
/*
    cell();
    cell(TCanvas par, int x=0,int y=0,int r=0, TColor bC=clBlack, TColor fC=clWhite, int bW=1);
    setParent(TCanvas*);
    setCoord(int,int);
    setRadius(int);
    setBorderColor(TColor);
    setFillColor(TColor);
    draw();
*/
 
const double k=0.866;
 
cell::cell()
{
    parent = NULL;
    TPoint _O(0,0);
    O = _O;
    r = 0;
    borderWidth = 1;
    borderColor = clBlack;
    fillColor = clWhite;
}
 
cell::cell(TCanvas* par, int _x, int _y,int _r, TColor bC, TColor fC, int bW)
{
    parent = par;
    TPoint _O(_x,_y);
    O = _O;
    r = 0;
    borderWidth = 1;
    borderColor = clBlack;
    fillColor = clYellow;
}
 
void cell::setParent(TCanvas* can)
{
    parent = can;
}
 
void cell::setCoord(int _x, int _y)
{
    O.x = _x;
    O.y = _y;
}
 
void cell::setCoord(TPoint P)
{
    O = P;
}
 
void cell::setRadius(int _r)
{
    r = _r;
}
 
void cell::setBorderColor(TColor col)
{
    borderColor = col;
}
 
void cell::setFillColor(TColor col)
{
    fillColor = col;
}
 
void cell::setBorderWidth(int bw)
{
    borderWidth = bw;
}
 
void cell::draw()
{
    TPoint cl[7];
    parent->Pen->Width = borderWidth;
    parent->Pen->Color = borderColor;
    parent->Brush->Color = fillColor;
 
    cl[0] = TPoint(O.x,O.y);
    cl[1] = TPoint(O.x+r/2, (int)(O.y+r*k));
    cl[2] = TPoint(O.x+3*r/2, (int)(O.y+r*k));
    cl[3] = TPoint(O.x+2*r, O.y);
    cl[4] = TPoint(O.x+3*r/2, (int)(O.y-r*k));
    cl[5] = TPoint(O.x+r/2, (int)(O.y-r*k));
    cl[6] = TPoint(O.x, O.y);
    parent->Polygon(cl,6);
}
 
TPoint cell::pointCoord(int n)
{
    switch (n) {
        case 0: return O; break;
        case 5: return TPoint(O.x+r/2, (int)(O.y+r*k)); break;
        case 4: return TPoint(O.x+3*r/2, (int)(O.y+r*k)); break;
        case 3: return TPoint(O.x+2*r, O.y); break;
        case 2: return TPoint(O.x+3*r/2, (int)(O.y-r*k)); break;
        case 1: return TPoint(O.x+r/2, (int)(O.y-r*k)); break;
    default:
        ;
    }
}
 
void cell::ShowText(UnicodeString s)
{
    parent->TextOutW((O.X+r-parent->TextWidth(s)/2),(O.Y-parent->TextHeight(s)/2),s);
}
 
//======================= C O M B ==============================================
 
comb::comb(TCanvas* par, int r, int c, TPoint O, int _rad)
{
    img = par;
    row = r;
    col = c;
    start = O;
    radius = _rad;
    g = new cell*[row];
    for (int i = 0; i < row; i++) {
        g[i] = new cell[col];
        for (int j = 0; j < col; j++) {
            g[i][j].setParent(img);
            //if (j==0)
            //g[i][j].setCoord(start.X,start.Y+(int)(i*2*k*r));
            //else
            g[i][j].setCoord(start.X+(int)(j*3*radius/2),
                    start.Y+(int)(i*2*k*radius)-(int)(j%2*radius*k));
            g[i][j].setRadius(radius);
            g[i][j].setBorderWidth(3);
        }
    }
}
 
void comb::draw(int r, int c)
{
    g[r][c].draw();
}
 
void comb::drawColor(int r, int c, TColor fc)
{
    g[r][c].setFillColor(fc);
    g[r][c].draw();
}
 
comb::~comb()
{
    for (int i = 0; i < row; i++) {
        delete [] g[i];
    }
    delete [] g;
}
 
void comb::paint()
{
    for(int i=0;i<row;i++)
    for(int j=0;j<col;j++)
        draw(i,j);
}
 
TPoint comb::getCoord(int X, int Y)
{
    int I = floor((Y-start.Y)/(k*radius)+2);
    int J = floor(((X-start.X)*cos(-M_PI/6)-(Y-start.Y)*sin(-M_PI/6))/(k*radius));
    int K = floor(((X-start.X)*cos(M_PI/6)-(Y-start.Y)*sin(M_PI/6))/(k*radius));
 
    int YY=(I-1)/2;
    if (I&&I%2==0) {
        if ((J-I/2)%3==1 && (K+I/2)%3==2) YY++;
        if ((J-I/2)%3==1 && (K+I/2)%3==0) YY++;
        if ((J-I/2)%3==2 && (K+I/2)%3==0) YY++;
    }
 
    int XX=-1;
    if ((K+YY)%3!=2)
    {
        XX=(K+YY)/3*2;
        if ((J-I/2)%3==1 && (K+I/2)%3==0) XX--;
        if ((J-I/2)%3==2 && (K+I/2)%3==0) XX--;
    }
    else XX = (K+YY-2)/3*2+1;
 
    return TPoint(XX,YY);
 
}
 
bool comb::inBounds(int ro, int co)
{
    return (ro<row && co<col);
}
 
bool comb::inBounds(TPoint P)
{
    return (P.Y<row && P.X<col);
}
 
cell& comb::operator()(int index, int jndex)
{
    if (index<row && jndex<col)
        return g[index][jndex];
}
 
int comb::getRow()
{
    return row;
}
 
int comb::getCol()
{
    return col;
}
 
/*
vector<int> comb::getNeighbors()
{
 
}
//*/
#pragma package(smart_init)
Добавлено через 1 минуту
CheshireCat, спасибо.
Надо же было так жостко тупануть.
0
Котовчанин
942 / 482 / 200
Регистрация: 16.02.2010
Сообщений: 3,338
Записей в блоге: 37
17.04.2015, 11:55 5
azbest, попробуйте
C++
1
std::vector<int> getNeighbors();
А, поздно написала.
0
4064 / 3318 / 924
Регистрация: 25.03.2012
Сообщений: 12,495
Записей в блоге: 1
17.04.2015, 12:03 6
C++
1
std::vector<int> getNeighbors();
написать никогда не поздно
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
17.04.2015, 12:49 7
На самом деле правильный ответ:
C++
std::vector<int> getNeighbors();
0
Тамика
17.04.2015, 13:11     Возврат vector из класса
  #8

Не по теме:

SatanaXIII, ну понеслась.:D

0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
17.04.2015, 13:11

Возврат значения объектом класса
Может ли экземпляр класса возвращать значение своего поля без обращения к полю напрямую например ...

Возврат объекта класса из функции
Имеется следующий код: #include &quot;stdafx.h&quot; #include &lt;iostream&gt; using namespace std; ...

Возврат функцией экземпляра класса
Подскажите, будет ли корректной с точки зрения выделения памяти и всего прочего такая запись:...

Виртуальная функция и возврат объекта класса
Доброго времени суток! Столкнулся с проблемой. Есть переопределенный оператор умножения в...


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

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