0 / 0 / 1
Регистрация: 01.10.2014
Сообщений: 87
1

Pure virtual function call (не видит переопределенный метод)

19.07.2016, 18:25. Показов 1259. Ответов 12
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте.
Имеется базовый класс Cars и унаследованные от него классы Jeep, Hatchback, Sedan
C++
1
2
3
4
5
6
7
8
9
//Cars.h
class Cars {
public:
    bool operator==(Cars &right);
    Cars &operator=(Cars &right);
    virtual double Score() = 0;
    virtual void Print() = 0;
    virtual ~Cars(){};
};
Соответственно, сделав чисто виртуальными функции Score и Print я обязуюсь их переопределить в унаследованных классах. Например, в Sedan
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include "Cars.h"
//Sedan.h
class Sedan :public Cars {
public:
    Sedan();
    Sedan(int cost, float road_clearance);
    Sedan(std::istream& is1, std::istream& is2);
    Sedan(const Sedan &orig);
    double Score();
    int Cost();
    int Speed();
    void Print();
    Sedan &operator=(Sedan &right);
    friend Sedan operator +(const Sedan &left, const Sedan &right);
    friend std::istream& operator>>(std::istream& is, Sedan &Sedan);
    friend std::ostream& operator<<(std::ostream &os, const Sedan &obj);
    ~Sedan();
 
private:
    int cost;
    int speed;
};
C++
1
2
3
void Sedan::Print() {
    std::cout << "S:" << cost << ", " << speed << std::endl;
}
Имеется свой контейнер типа очередь, в котором промежуточным звеном между самим контейнером и тем, что в нем хранится, является класс TQueueItem
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "Cars.h"
#include "Jeep.h"
#include "Sedan.h"
#include "Hatchback.h"
 
//TQueueItem.h
class TQueueItem {
public:
    TQueueItem();
    TQueueItem(Cars& car);
    TQueueItem(TQueueItem& orig);
    friend std::ostream& operator<<(std::ostream& os, const TQueueItem& obj);
    
    TQueueItem *GetNext();
    Cars *GetCar() const ;
    ~TQueueItem();
    TQueueItem *next;
private:
    Cars *car;
};
И, наконец, сам контейнер
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
#include <iostream>
#include "Jeep.h"
#include "TQueueItem.h"
 
//Queue.h
class TQueue {
public:
    TQueue();
    TQueue(const TQueue &orig);
 
    TQueue(Cars &car);
    int GetSize();
    void PushBack(Cars &car);
    void PushBack(Cars *car); 
    Cars *PopFront();
    bool Empty();
    friend std::ostream& operator<<(std::ostream &os, const TQueue &queue);
    
    void ISize();
    void DSize();
    
    ~TQueue();
    
private:
    TQueueItem *head;
    TQueueItem *tail;
 
    int size;   
};
Проблема состоит в том, что если я добавляю элемент: q.PushBack(Hatchback()):
C++
1
2
3
4
5
6
7
8
9
void TQueue::PushBack(Cars &car) {
    TQueueItem *item = new TQueueItem(car);
    item->next = nullptr;
    tail->next = item;
    tail = item;
    tail->GetCar()->Print();//здесь все правильно выводится
    delete item;
    size++;
}
Однако при попытке вывести содержимое очереди std::cout << q;:
C++
1
2
3
4
5
6
7
8
9
10
std::ostream& operator<<(std::ostream &os, const TQueue &queue) {
    //if (queue.size != 0) {
    std::cout << "in print" << std::endl;
    TQueueItem *ptr = queue.head;
    while (ptr != nullptr) {
        os << (*ptr) << std::endl; //если здесь ptr->GetCar()->Print(), то тоже virtual function call
        ptr = ptr->GetNext();
    }
    return os;
}
Отсюда переходим в
C++
1
2
3
4
5
6
std::ostream &operator<<(std::ostream& os, const TQueueItem &obj) {
    os << "[";
    obj.GetCar()->Print();//virtual function call
    os<< "] ";
    return os;
}
Вопрос: почему при добавлении все нормально, а при выводе - нет. Как сделать так, чтобы этой ошибки не было?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
19.07.2016, 18:25
Ответы с готовыми решениями:

R6025 pure virtual function call
Ошибка - r6025 pure virtual function call. Что не так? #include &lt;iostream&gt; #include &lt;cstring&gt;...

R6025 pure virtual function call при вызове метода, реализованного в дочернем классе
Всем привет. Вот такая ошибка у меня возникает при вызове метода, который реализован в дочернем...

Pure virtual function definition (C++11)
Объясните мне, как ламеру, для чего может понадобится определение чисто виртуальной функции?

Что означает ошибка pure virtual function call в NFS?
Что означает ошибка pure virtual function call?

12
Неэпический
17850 / 10618 / 2049
Регистрация: 27.09.2012
Сообщений: 26,689
Записей в блоге: 1
19.07.2016, 18:46 2
C++
1
2
3
    tail = item;//запхнули указатель
    //...
    delete item;//удалили объект.
вопрос - куда теперь "указывает" указатель в контейнере?
0
0 / 0 / 1
Регистрация: 01.10.2014
Сообщений: 87
19.07.2016, 19:02  [ТС] 3
Croessmah, на область памяти, которой процесс больше не владеет. Согласен, ошибка грубая. Но главная проблема так и осталась.
0
Эксперт С++
1673 / 1045 / 174
Регистрация: 27.09.2009
Сообщений: 1,945
19.07.2016, 20:49 4
mishula, а если убрать скобки вокруг *ptr при выводе в operator <<, проблема решится?
0
Эксперт С++
8738 / 4316 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
19.07.2016, 20:56 5
Цитата Сообщение от mishula Посмотреть сообщение
почему при добавлении все нормально, а при выводе - нет.
телепаты в отпуске.

Цитата Сообщение от mishula Посмотреть сообщение
Как сделать так, чтобы этой ошибки не было?
привести минимальный компилирующийся пример,
который иллюстрирует вашу проблему.

код можно выложить например здесь:
http://rextester.com/DMXZPL35906
0
0 / 0 / 1
Регистрация: 01.10.2014
Сообщений: 87
19.07.2016, 22:57  [ТС] 6
hoggy, пожалуйста http://rextester.com/AKYR81265
Nick Alte, это ничего не меняет
0
Неэпический
17850 / 10618 / 2049
Регистрация: 27.09.2012
Сообщений: 26,689
Записей в блоге: 1
19.07.2016, 23:10 7
Цитата Сообщение от mishula Посмотреть сообщение
пожалуйста
Такое не будет компилироваться нигде окромя студии.
Что касается кода, то он вообще какой-то кривой.
0
Эксперт С++
1673 / 1045 / 174
Регистрация: 27.09.2009
Сообщений: 1,945
19.07.2016, 23:17 8
mishula, посмотрел код внимательнее. Проблема в конструкторе TQueueItem(Cars&);, который получает адрес временного объекта Sedan, который уничтожается сразу после использования (а адрес продолжает использоваться в созданном TQueueItem).
0
Неэпический
17850 / 10618 / 2049
Регистрация: 27.09.2012
Сообщений: 26,689
Записей в блоге: 1
19.07.2016, 23:29 9
Nick Alte, именно.
Причем если бы компилятор так расхлябано к этому не относился,
а соответствовал требованиям, то он бы такого не допустил.
Я имею ввиду потерю константности и
привязку временного объекта к неконстантной ссылке.
Конечно, поломать можно всё, но этот компилятор просто этому способствует.
0
Эксперт С++
8738 / 4316 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
19.07.2016, 23:41 10
Цитата Сообщение от mishula Посмотреть сообщение
пожалуйста
временный объект:
C++
1
TQueue q(Sedan(1000000,120));
передаёт элементу очереди:
C++
1
2
void TQueue::PushBack(Cars &car) {
    TQueueItem *item = new TQueueItem(car);
где элемент очереди срисовывает указатель на этот объект:
C++
1
2
3
TQueueItem::TQueueItem(Cars &cars):car(&cars),next(nullptr) {
    std::cout << "Queue item: created" << std::endl;
}
как только все выражение выполняется,
временный объект умирает,
в итоге имеем указатель на труп.

лекарство:
http://rextester.com/MXDHR6587
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#include <iostream>
 
class Cars {
public:
    Cars &operator=(Cars &right);
    virtual void Print() = 0;
    virtual ~Cars(){};
    
    virtual Cars* Clone()const = 0;
};
 
class Sedan :public Cars {
public:
    Sedan();
    Sedan(int cost, float road_clearance);
    Sedan(std::istream& is1, std::istream& is2);
    Sedan(const Sedan &orig);
    void Print();
    Sedan &operator=(Sedan &right);
    friend std::istream& operator>>(std::istream& is, Sedan &Sedan);
    friend std::ostream& operator<<(std::ostream &os, const Sedan &obj);
    ~Sedan();
    
    virtual Cars* Clone()const override
    {
        return new Sedan(*this);
    }
private:
    int cost;
    int speed;
};
 
Sedan::Sedan() :Sedan(1000000, 10.8) {
}
 
Sedan::Sedan(int a, float b) : cost(a), speed(b) {
    std::cout << "Sedan created" << std::endl;
}
 
Sedan::Sedan(std::istream& is1, std::istream &is2) {
    is1 >> cost;
    is2 >> speed;
}
 
Sedan::Sedan(const Sedan &orig) {
    cost = orig.cost;
    speed = orig.speed;
    std::cout << "Sedan copy created" << std::endl;
}
 
void Sedan::Print() {
    std::cout << "S:" << cost << ", " << speed << std::endl;
}
 
Sedan& Sedan::operator=(Sedan &right) {
    if (this == &right)
        return *this;
    (*this).cost = right.cost;
    (*this).speed = right.speed;
    std::cout << "operator =: success" << std::endl;
    return (*this);
}
 
std::istream &operator>>(std::istream &is, Sedan &Sedan) {
    is >> Sedan.cost;
    is >> Sedan.speed;
    return is;
}
 
std::ostream& operator<<(std::ostream& os, const Sedan &Sedan) {
    std::cout << Sedan.cost << ", " << Sedan.speed;
    return os;
}
 
Sedan::~Sedan(){
    std::cout << "Sedan deleted" << std::endl;
}    
    
class TQueueItem {
public:
    TQueueItem();
    TQueueItem(Cars& car);
    TQueueItem(TQueueItem& orig);
    friend std::ostream& operator<<(std::ostream& os, const TQueueItem& obj);
    
    TQueueItem *GetNext();
    Cars *GetCar() const ;
    ~TQueueItem();
    TQueueItem *next;
private:
    Cars *car;
};
 
TQueueItem::TQueueItem() : car(nullptr), next(nullptr){}
 
TQueueItem::TQueueItem(Cars &cars):car(cars.Clone()) ,next(nullptr) {
    std::cout << "Queue item: created" << std::endl;
}
 
TQueueItem::TQueueItem(TQueueItem& orig) {
    car = orig.car;
    next = orig.next;
}
 
Cars *TQueueItem::GetCar() const {
    return this->car;
}
 
TQueueItem* TQueueItem::GetNext() {
    return this->next;
}
 
std::ostream &operator<<(std::ostream& os, const TQueueItem &obj) {
    os << "[";
    obj.GetCar()->Print();
    os<< "] ";
    return os;
}
 
TQueueItem::~TQueueItem() {
    delete car;
    std::cout << "Queue item: deleted" << std::endl;
}
 
class TQueue {
public:
    TQueue();
    TQueue(const TQueue &orig);
    TQueue(Cars &car);
    int GetSize();
    void PushBack(Cars &car);
    void PushBack(Cars *car);
    Cars *PopFront();
    bool Empty();
    friend std::ostream& operator<<(std::ostream &os, const TQueue &queue);
    
    void ISize();
    void DSize();
    
    ~TQueue();
    
private:
    TQueueItem *head;
    TQueueItem *tail;
 
    int size;   
};
 
TQueue::TQueue() :head(nullptr), tail(nullptr), size(0){ /*head = tail;*/ }
 
TQueue::TQueue(const TQueue &orig) {
    head = orig.head;
    tail = orig.tail;
    size = orig.size;
}
 
 
 
TQueue::TQueue(Cars &car) {
    head = tail = new TQueueItem(car);
    size = 1;
    tail->next = nullptr;
    tail->GetCar()->Print();
}
 
 
std::ostream& operator<<(std::ostream &os, const TQueue &queue) {
    std::cout << "in print" << std::endl;
    TQueueItem *ptr = queue.head;
    while (ptr != nullptr) {
        os << *ptr << std::endl;
        
        ptr = ptr->GetNext();
    }
    return os;
}
 
void TQueue::PushBack(Cars &car) {
 
    TQueueItem *item = new TQueueItem(car);
    item->next = nullptr;
    tail->next = item;
    tail = item;
    tail->GetCar()->Print();
    size++;
}
 
void TQueue::PushBack(Cars *car) {
    
    TQueueItem *item = new TQueueItem(*car);
    item->next = nullptr;
    tail->next = item;
    tail = item;
    tail->GetCar()->Print();
    
    size++;
}
 
 
Cars *TQueue::PopFront() {
    static Cars *car;
    TQueueItem *tmp = head;
    if (head != nullptr)
         car = tmp->GetCar();
    head = head->GetNext();
    delete tmp;
    DSize();
    
    return car;
}
 
int TQueue::GetSize() {
    return size;
}
 
void TQueue::ISize() {
    size++;
}
 
void TQueue::DSize() {
    if (size>0)
        size--;
}
 
bool TQueue::Empty() {
    return (head == nullptr);
}
 
TQueue::~TQueue() {
    delete head;
}
 
int main()
{
    TQueue q(Sedan(1000000,120));
    q.PushBack(Sedan(3400000, 210));
    Cars *car1 = new Sedan();
    q.PushBack(car1);
    std::cout << q;
}
0
0 / 0 / 1
Регистрация: 01.10.2014
Сообщений: 87
19.07.2016, 23:44  [ТС] 11
hoggy, спасибо, сейчас посмотрю. Сам я пока додумался только для использования в main
C++
1
q.PushBack(new Sedan(3400000, 210));
0
Эксперт С++
1673 / 1045 / 174
Регистрация: 27.09.2009
Сообщений: 1,945
20.07.2016, 00:01 12
Цитата Сообщение от Croessmah Посмотреть сообщение
Причем если бы компилятор так расхлябано к этому не относился,
а соответствовал требованиям, то он бы такого не допустил.
Да, здесь явно отклонение от стандарта. Впрочем, удивляться не приходится, это же Visual C++, печально известный огрехами такого рода.
0
Эксперт С++
8738 / 4316 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
20.07.2016, 00:06 13
Цитата Сообщение от Nick Alte Посмотреть сообщение
это же Visual C++, печально известный огрехами такого рода.
нет, это программисты, печально известные игнорированием
предупреждений от компилятора.
http://rextester.com/RSHOKM68850
Warning(s):
source_file.cpp(28): warning C4305: 'argument': truncation from 'double' to 'float'
source_file.cpp(31): warning C4244: 'initializing': conversion from 'float' to 'int', possible loss of data
source_file.cpp(229): warning C4239: nonstandard extension used: 'argument': conversion from 'Sedan' to 'Cars &'
source_file.cpp(229): note: A non-const reference may only be bound to an lvalue
source_file.cpp(230): warning C4239: nonstandard extension used: 'argument': conversion from 'Sedan' to 'Cars &'
source_file.cpp(230): note: A non-const reference may only be bound to an lvalue
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
20.07.2016, 00:06
Помогаю со студенческими работами здесь

Protected abstract virtual base pure virtual private destructor
Хай, all) Вопрос не для начинающих и дурацкий) В разделе для экспертов публиковать не стал, чтобы...

Статический метод DB (Ошибка: Call to a member function query() on null)
Здравствуйте! Хочу сделать класс базы данный статическим, переписывают весь класс, вот это метод:...

Pure virtual method called - deleteLater
Всем добрый день! не могу самостоятельно понять почему возникает ошибка pure virtual method called...

Call to undefined function '_beginthreadex' in function main()
Здесь реализуется задача о 5-ти китайских философах, обедающих за столом #include&lt;windows.h&gt; ...


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

Или воспользуйтесь поиском по форуму:
13
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru