Перейти к содержанию
СофтФорум - всё о компьютерах и не только

virtual и operator<< в c++


Рекомендуемые сообщения

всем привет, как сделать так, чтобы перегруженный operator<< выполнялся для объекта нужного типа в функциях Stack::peek() и Stack::pop(), дружественные функции не могут быть виртуальными, а если перегрузить operator<<, как не дружественную функцию и объявить ее виртуальной, то решение получается не очень красивым, кто знает подскажите, пожалуйста, другой способ если, кончено, он есть

class Shape {   public:       Shape() cout << "Shape constructor\n";}       virtual ~Shape() {cout << "Shape destructor\n";}       virtual void draw() {cout << "Shape::draw\n";}       friend ostream& operator<<(ostream& os, const Shape& c) {           return os << "Shape::operator<<\n";       }};class Circle : public Shape {   public:       Circle() {cout << "Circle constructor\n";}       ~Circle() {cout << "Circle destructor\n";}       void draw() {cout << "Circle::draw\n";}       friend ostream& operator<<(ostream& os, const Circle&) {           return os << "Circle::operator<<\n";       }};class Square : public Shape {   public:       Square() {cout << "Square constructor\n";}       ~Square() {cout << "Square destructor\n";}       void draw() {cout << "Square::draw\n";}       friend ostream& operator<<(ostream& os, const Square&) {           return os << "Square::operator<<\n";       }};class Triangle : public Shape {   public:       Triangle() {cout << "Triangle constructor\n";}       ~Triangle() {cout << "Triangle destructor\n";}       void draw() {cout << "Triangle::draw\n";}       friend ostream& operator<<(ostream& os, const Triangle&) {           return os << "Triangle::operator<<\n";       }};class Stack {   private:       struct Link {           Shape* data;           Link* next;           Link(Shape* dat, Link* nxt) : data(dat), next(nxt) {}       }* head;       int sz;   public:       Stack() : head(0), sz(0) {}       ~Stack();       void push(Shape* dat) {           head = new Link(dat, head);           sz++;       }       Shape* peek() const {           return head ? head->data : 0;       }       Shape* pop();       int size() {return sz;}};Stack::~Stack() {   while (head)      pop();}Shape* Stack::pop() {   if (head == 0) return 0;   Shape* result = head->data;   Link* oldHead = head;   head = head->next;   delete oldHead;   sz--;   return result;}
Ссылка на комментарий
Поделиться на другие сайты

  • 2 недели спустя...
The major disadvantage of friend functions is that they require an extra line of code when you want dynamic binding. To get the effect of a virtual friend, the friend function should call a hidden (usually protected) virtual member function. This is called the Virtual Friend Function Idiom.

Если не понимаете английского, здесь предлагають чтоби operator << делал

c.cout (примерно)

class Shape {   public:       Shape() cout << "Shape constructor\n";}       virtual ~Shape() {cout << "Shape destructor\n";}       virtual void draw() {cout << "Shape::draw\n";}       friend ostream& operator<<(ostream& os, const Shape& c) {           return c.cout(os);       }   protected:        virttual ostream& count(ostream& os){           return os << "Shape::operator<<\n";        }};
Ссылка на комментарий
Поделиться на другие сайты

  • 1 месяц спустя...

спасибо, я понял, что написано на англ, но только у меня все равно вызывается метод Shape

Ссылка на комментарий
Поделиться на другие сайты

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.

Гость
Ответить в этой теме...

×   Вставлено с форматированием.   Вставить как обычный текст

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

  • Последние посетители   0 пользователей онлайн

    • Ни одного зарегистрированного пользователя не просматривает данную страницу
×
×
  • Создать...